Haskell 99 Problems - Number 20, Arrowed!


/ Published in: Haskell
Save to your folder(s)

problem 20, (*) Remove the K'th element from a list

*Main> removeAt 1 "abcd"
"acd"

Trivial using a pure function. A bit more challenging if you use this problem to work up your Arrow-fu.


Copy this code and paste it in your HTML
  1. {-# LANGUAGE Arrows #-}
  2. import Control.Arrow
  3. import Data.List
  4.  
  5. list = "abcdefghijklmnop"
  6.  
  7. -- the trivial version
  8. removeAt n xs = take (n-1) xs ++ (drop n) xs
  9.  
  10. -- now new and improved! with Arrows for ultra-obfuscation!
  11. removeAt' :: (Arrow cat) => Int -> cat [a] [a]
  12. removeAt' n = arr(\ xs -> (xs,xs)) >>> arr (take (n-1)) *** arr (drop n)
  13. >>> arr (uncurry (++)) >>> returnA
  14.  
  15. {-
  16.   the arrowed function is easier to understand in its sugary form
  17.   NOTE: the head and tail of the arrows are lambda values, so they
  18.   can't be used inside the arrow's machinery. Also, to use this
  19.   notation, you'll need the LANGUAGE Arrows pragma
  20. -}
  21. removeAt'' :: Int -> [a] -> [a]
  22. removeAt'' n = proc things -> do
  23. (begin, end) <- (\xs -> (xs, xs)) -< things
  24. begin' <- take (n-1) -< begin
  25. end' <- drop n -< end
  26. newlist <- uncurry (++) -< (begin', end')
  27. returnA -< newlist
  28.  
  29. -- This is equivalent, and shows how proc notation can
  30. -- simplify things
  31. removeAt''' :: Int -> [a] -> [a]
  32. removeAt''' n = proc things -> do
  33. begin <- take (n-1) -< things
  34. end <- drop n -< things
  35. returnA -< begin ++ end
  36.  
  37. main = do
  38. putStrLn list
  39. putStrLn $ removeAt 3 list
  40. putStrLn $ removeAt' 5 list
  41. putStrLn $ removeAt'' 9 list

URL: http://haskell.org/haskellwiki/99_questions/11_to_20

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.