Difference between revisions of "Blow your mind"

From HaskellWiki
Jump to navigation Jump to search
(more links on polynomials)
(Add case)
(40 intermediate revisions by 22 users not shown)
Line 6: Line 6:
   
   
== List/String Operations ==
+
== List/String operations ==
   
   
Line 14: Line 14:
 
words
 
words
   
takeWhile (not . null) . unfoldr (Just . (second $ drop 1) . break (==' '))
+
unfoldr (\b -> fmap (const . (second $ drop 1) . break (==' ') $ b) . listToMaybe $ b)
  +
  +
takeWhile (not . null) . evalState (repeatM $ modify (drop 1) >> State (break (== ' '))) . (' ' :)
  +
where repeatM = sequence . repeat
   
 
fix (\f l -> if null l then [] else let (s,e) = break (==' ') l in s:f (drop 1 e))
 
fix (\f l -> if null l then [] else let (s,e) = break (==' ') l in s:f (drop 1 e))
Line 21: Line 24:
 
-- splitting in two (alternating)
 
-- splitting in two (alternating)
 
-- "1234567" -> ("1357", "246")
 
-- "1234567" -> ("1357", "246")
  +
-- the lazy match with ~ is necessary for efficiency, especially enabling processing of infinite lists
foldr (\a (x,y) -> (a:y,x)) ([],[])
 
  +
foldr (\a ~(x,y) -> (a:y,x)) ([],[])
   
 
(map snd *** map snd) . partition (even . fst) . zip [0..]
 
(map snd *** map snd) . partition (even . fst) . zip [0..]
   
transpose . unfoldr (\a -> if null a then Nothing else Just $ splitAt 2 a)
+
transpose . unfoldr (\a -> toMaybe (null a) (splitAt 2 a))
 
-- this one uses the solution to the next problem in a nice way :)
 
-- this one uses the solution to the next problem in a nice way :)
 
 
  +
toMaybe b x = if b then Just x else Nothing
  +
-- or generalize it:
  +
-- toMaybe = (toMonadPlus :: Bool -> a -> Maybe a)
  +
toMonadPlus b x = guard b >> return x
   
 
-- splitting into lists of length N
 
-- splitting into lists of length N
 
-- "1234567" -> ["12", "34", "56", "7"]
 
-- "1234567" -> ["12", "34", "56", "7"]
unfoldr (\a -> if null a then Nothing else Just $ splitAt 2 a)
+
unfoldr (\a -> toMaybe (not $ null a) (splitAt 2 a))
   
 
takeWhile (not . null) . unfoldr (Just . splitAt 2)
 
takeWhile (not . null) . unfoldr (Just . splitAt 2)
  +
  +
ensure :: MonadPlus m => (a -> Bool) -> a -> m a
  +
ensure p x = guard (p x) >> return x
  +
unfoldr (ensure (not . null . fst) . splitAt 2)
 
 
   
 
-- sorting by a custom function
 
-- sorting by a custom function
 
-- length -> ["abc", "ab", "a"] -> ["a", "ab", "abc"]
 
-- length -> ["abc", "ab", "a"] -> ["a", "ab", "abc"]
comparing f x y = compare (f x) (f y)
+
comparing f = compare `on` f -- "comparing" is already defined in Data.Ord
 
sortBy (comparing length)
 
sortBy (comparing length)
   
Line 46: Line 58:
   
 
-- comparing adjacent elements
 
-- comparing adjacent elements
rises xs = zipWith (<) xs (drop 1 xs)
+
rises xs = zipWith (<) xs (tail xs)
 
 
 
-- lazy substring search
 
-- lazy substring search
Line 55: Line 67:
 
-- splitAts [2,5,0,3] [1..15] == [[1,2],[3,4,5,6,7],[],[8,9,10],[11,12,13,14,15]]
 
-- splitAts [2,5,0,3] [1..15] == [[1,2],[3,4,5,6,7],[],[8,9,10],[11,12,13,14,15]]
 
splitAts = foldr (\n r -> splitAt n >>> second r >>> uncurry (:)) return
 
splitAts = foldr (\n r -> splitAt n >>> second r >>> uncurry (:)) return
  +
  +
-- frequency distribution
  +
-- "abracadabra" -> fromList [('a',5),('b',2),('c',1),('d',1),('r',2)]
  +
import Data.Map
  +
histogram = fromListWith (+) . (`zip` repeat 1)
  +
  +
-- using arrows and sort
  +
histogramArr = map (head&&&length) . group . sort
  +
  +
-- multidimensional zipWith
  +
zip2DWith :: (a -> b -> c) -> [[a]] -> [[b]] -> [[c]]
  +
zip2DWith = zipWith . zipWith
  +
zip3DWith :: (a -> b -> c) -> [[[a]]] -> [[[b]]] -> [[[c]]]
  +
zip3DWith = zipWith . zipWith . zipWith
  +
-- etc.
 
</haskell>
 
</haskell>
   
== Mathematical Sequences, etc ==
+
== Mathematical sequences, etc ==
   
   
Line 65: Line 92:
 
product [1..6]
 
product [1..6]
   
foldl1 (*) [1..6]
+
foldl1 (*) [1..6] -- this won't work for 0; use "foldl (*) 1 [1..n]" instead
   
 
(!!6) $ scanl (*) 1 [1..]
 
(!!6) $ scanl (*) 1 [1..]
Line 83: Line 110:
 
fibs = 0:1:zipWith (+) fibs (tail fibs)
 
fibs = 0:1:zipWith (+) fibs (tail fibs)
   
fib = 0:scanl (+) 1 fib
+
fib = 0:scanl (+) 1 fib -- also seen as: fibs = fix ((0:) . scanl (+) 1)
   
   
Line 97: Line 124:
 
unfoldr sieve [2..] where
 
unfoldr sieve [2..] where
 
sieve (p:x) = Just(p, [ n | n <- x, n `mod` p > 0 ])
 
sieve (p:x) = Just(p, [ n | n <- x, n `mod` p > 0 ])
  +
  +
otherPrimes = nubBy (((>1).).gcd) [2..]
   
 
-- or if you want to use the Sieve of Eratosthenes..
 
-- or if you want to use the Sieve of Eratosthenes..
Line 112: Line 141:
 
rats = iterate next 1 where
 
rats = iterate next 1 where
 
next x = recip (fromInteger n+1-y) where (n,y) = properFraction x
 
next x = recip (fromInteger n+1-y) where (n,y) = properFraction x
  +
  +
-- another way
  +
rats2 = fix ((1:) . (>>= \x -> [1+x, 1/(1+x)])) :: [Rational]
 
</haskell>
 
</haskell>
   
 
[1] [http://web.comlab.ox.ac.uk/oucl/work/jeremy.gibbons/publications/index.html#rationals Gibbons, Lest, Bird - Enumerating the Rationals]
 
[1] [http://web.comlab.ox.ac.uk/oucl/work/jeremy.gibbons/publications/index.html#rationals Gibbons, Lest, Bird - Enumerating the Rationals]
   
== Monad Magic ==
+
== Monad magic ==
   
  +
The list monad can be used for some amazing Prolog-ish search problems.
   
 
<haskell>
 
<haskell>
Line 132: Line 165:
   
 
"12" >>= \a -> "45" >>= \b -> return [a,b]
 
"12" >>= \a -> "45" >>= \b -> return [a,b]
 
   
 
-- all combinations of letters
 
-- all combinations of letters
 
(inits . repeat) ['a'..'z'] >>= sequence
 
(inits . repeat) ['a'..'z'] >>= sequence
   
 
 
-- apply a list of functions to an argument
 
-- apply a list of functions to an argument
 
-- even -> odd -> 4 -> [True,False]
 
-- even -> odd -> 4 -> [True,False]
Line 143: Line 174:
   
 
sequence [even,odd] 4
 
sequence [even,odd] 4
  +
 
  +
-- all subsequences of a sequence/ aka powerset.
  +
filterM (const [True, False])
   
 
-- apply a function to two other function the same argument
 
-- apply a function to two other function the same argument
Line 152: Line 185:
 
liftM2 (>>) putStrLn return "hello"
 
liftM2 (>>) putStrLn return "hello"
   
  +
fix ((1:) . (>>= \x -> [x+1, 1/(x+1)])) :: [Rational]
  +
[1%1,2%1,1%2,3%1,1%3,3%2,2%3,4%1,1%4,4%3,3%4,5%2,2%5,5%3,3%5,5%1,1%5,5%4,4%5...
 
 
 
-- forward function concatenation
 
-- forward function concatenation
Line 166: Line 201:
   
 
-- [still to categorize]
 
-- [still to categorize]
(id >>= (+) >>= (+) >>= (+)) 3 -- (3+3)+(3+3) = 12
+
(id >>= (+) >>= (+) >>= (+)) 3 -- 3+3+3+3 = 12
  +
-- Note: need to import Control.Monad.Instances
   
  +
(join . liftM2) (*) (+3) 5 -- 64
 
  +
-- Galloping horsemen
  +
-- A large circular track has only one place where horsemen can pass;
  +
-- many can pass at once there. Is it possible for nine horsemen to
  +
-- gallop around it continuously, all at different constant speeds?
  +
-- the following prints out possible speeds for 2 or more horsemen.
  +
spd s = ' ': show s ++ '/': show (s+1)
  +
ext (c,l) = [(tails.filter(\b->a*(a+1)`mod`(b-a)==0)$r,a:l) | (a:r)<-c]
  +
put = putStrLn . ('1':) . concatMap spd . reverse . snd . head
  +
main = mapM_ put . iterate (>>= ext) $ [(map reverse $ inits [1..],[])]
  +
  +
-- output:
  +
1 1/2
  +
1 2/3 1/2
  +
1 3/4 2/3 1/2
  +
1 5/6 4/5 3/4 2/3
  +
1 12/13 11/12 10/11 9/10 8/9
  +
1 27/28 26/27 25/26 24/25 23/24 20/21
  +
1 63/64 60/61 59/60 57/58 56/57 55/56 54/55
  +
1 755/756 741/742 740/741 735/736 734/735 728/729 727/728 720/721
  +
1 126224/126225 122759/122760 122549/122550 122528/122529 122451/122452
  +
122444/122445 122374/122375 122304/122305 122264/122265
  +
  +
  +
double = join (+)
  +
  +
(join . liftM2) (*) (+3) 5 -- (5+3)*(5+3) = 64
  +
-- Note: need to import Control.Monad.Instances
   
 
mapAccumL (\acc n -> (acc+n,acc+n)) 0 [1..10] -- interesting for fac, fib, ...
 
mapAccumL (\acc n -> (acc+n,acc+n)) 0 [1..10] -- interesting for fac, fib, ...
Line 176: Line 239:
 
do { Just x <- [Nothing, Just 5, Nothing, Just 6, Just 7, Nothing]; return x }
 
do { Just x <- [Nothing, Just 5, Nothing, Just 6, Just 7, Nothing]; return x }
 
</haskell>
 
</haskell>
 
   
 
== Other ==
 
== Other ==
Line 187: Line 249:
 
| otherwise -> True
 
| otherwise -> True
   
  +
--or:
  +
cond = foldr (uncurry if') -- see [1] below
   
 
-- match a constructor
 
-- match a constructor
Line 193: Line 257:
 
case a of Just{} -> True
 
case a of Just{} -> True
 
_ -> False
 
_ -> False
  +
  +
  +
-- spreadsheet magic
  +
-- requires import Control.Monad.Instances
  +
let loeb x = fmap ($ loeb x) x in
  +
loeb [ (!!5), const 3, liftM2 (+) (!!0) (!!1), (*2) . (!!2), length, const 17]
   
   
Line 208: Line 278:
 
-}
 
-}
 
</haskell>
 
</haskell>
  +
  +
[1]: see [[Case]] and [[If-then-else]].
   
 
=== Polynomials ===
 
=== Polynomials ===
In abstract algebra you learn that polynomials can be used the same way integers are used given the right assumptions about their coefficients and roots. Specifically, polynomials support addition, subtraction, multiplication and sometimes division. It also turns out that one way to think of polynomials is that they are just lists of numbers (their coefficients). Here is one way to use lists to model polynomials. Since polynomials can support the same operations as integers, we model polynomials by making a list of numbers an instance of the Num type class.
+
In abstract algebra you learn that polynomials can be used the same way integers are used given the right assumptions about their coefficients and roots. Specifically, polynomials support addition, subtraction, multiplication and sometimes division. It also turns out that one way to think of polynomials is that they are just lists of numbers (their coefficients).
   
  +
instance Num a => Num [a] where -- (1)
<haskell>
 
-- First we tell Haskell that we want to make lists (or [a]) an instance of Num.
 
-- We refer to this instance of the Num type class as Num [a].
 
-- If you tried to use just:
 
-- "instance Num [a] where"
 
-- You'd get errors because the element type a is too general, too unconstrainted
 
-- for what we need.
 
-- So we add constraints to "a" by saying "Num a", this means whatever "a" is, it
 
-- must be in the Num type class.
 
   
  +
(f:fs) + (g:gs) = f+g : fs+gs -- (2)
instance Num a => Num [a] where
 
  +
fs + [] = fs -- (3a)
-- Next, we have to implement all the operations that instances of Num support.
 
  +
[] + gs = gs -- (3b)
-- A minimal set of operations is +, *, negate, abs, signum and fromInteger.
 
  +
xs + ys = zipWith' (+) xs ys
 
  +
(f:fs) * (g:gs) = f*g : [f]*gs + fs*(g:gs) -- (4)
where
 
  +
_ * _ = [] -- (5)
zipWith' f [] ys = ys
 
  +
zipWith' f xs [] = xs
 
  +
abs = undefined -- I can't think of a sensible definition
zipWith' f (x:xs) (y:ys) = f x y : zipWith' f xs ys
 
  +
signum = map signum
-- We define a new version of zipWith that returns a list as long as the longest
 
  +
fromInteger n = [fromInteger n]
-- of the two lists it is given. If we did not do this then when we add polynomials
 
  +
negate = map (\x -> -x)
-- the result would be truncated to the length of the shorter polynomial.
 
  +
xs * ys = foldl1 (+) (padZeros partialProducts)
 
  +
====Explanation====
where
 
  +
(1) puts lists into type class Num, the class to which operators + and * belong, provided the list elements are in class Num.
partialProducts = map (\x -> [x*y | y <- ys]) xs
 
  +
padZeros = map (\(z,zs) -> replicate z 0 ++ zs) . (zip [0..])
 
  +
Lists are ordered by increasing powers. Thus <tt>f:fs</tt> means <tt>f+x*fs</tt> in algebraic notation. (2) and (4) follow from these algebraic identities:
-- This function is sort of hard to explain.... basically [1,2,3] should correspond
 
  +
-- to the polynomial 1 + 2x + 3x^2. partialProducts does the steps of the multiplication
 
  +
(f+x*fs) + (g+x*gs) = f+g + x*(fs+gs)
-- just like you would by hand when multiplying polynomials.
 
  +
(f+x*fs) * (g+x*gs) = f*g + x*(f*gs + fs*(g+x*gs))
-- padZeros takes a list of polynomials and creates tuples of the form
 
  +
-- (offset, poly). If you notice when you add the partial products by hand
 
  +
(3) and (5) handle list ends.
-- that you have to shift the partial products to the left on each new line.
 
  +
-- we accomplish this by padding by zeros at the beginning of the partial product.
 
  +
The bracketed <tt>[f]</tt> in (4) avoids mixed arithmetic, which Haskell doesn't support.
-- Finally we use foldl1 to sum the partial products. Since they are polynomials
 
  +
-- They are added by the definition of plus we already gave.
 
  +
====Comments====
negate xs = map negate xs
 
  +
abs xs = map abs xs -- is this reasonable?
 
  +
The methods are qualitatively different from ordinary array-based methods; there is no vestige of subscripting or counting of terms.
signum xs = fromIntegral ((length xs)-1)
 
  +
-- signum isn't really defined for polynomials, but polynomials do have a concept
 
  +
The methods are suitable for on-line computation. Only
-- of degree. We might as well reuse signum as the degree of the
 
  +
<i>n</i> terms of each input must be seen before the <i>n</i>-th term
-- the polynomial. Notice that constants have degree zero.
 
  +
of output is produced.
fromInteger x = [fromInteger x]
 
  +
-- This definition of fromInteger seems cyclical, it is left
 
  +
Thus the methods work on infinite series as well as polynomials.
-- as an exercise to the reader to figure out why it is correct :)
 
  +
</haskell>
 
  +
Integer power comes for free. This example tests the cubing of (1+x):
The reader is encouraged to write a simple pretty printer that takes into account the many special cases of displaying a polynomial. For example, [1,3,-2, 0, 1,-1,0] should display as: <tt>-x^5 + x^4 - 2x^2 + 3x + 1</tt>
 
  +
  +
[1, 1]^3 == [1, 3, 3, 1]
  +
  +
  +
This gives us the infinite list of rows of Pascal's triangle:
  +
  +
pascal = map ([1,1]^) [0..]
  +
  +
For example,
   
  +
take 5 pascal -- [[1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1]]
Other execrises for the reader include writing <haskell>polyApply :: (Num a) => [a] -> a -> a </haskell> which evaluates the polynomial at a specific value or writing a differentiation function.
 
   
 
See also
 
See also
 
* [[Pointfree]]
 
* [[Pointfree]]
* [http://darcs.haskell.org/numericprelude/src/MathObj/Polynomial.lhs NumericPrelude: Polynomials]
+
* [http://darcs.haskell.org/numericprelude/src/MathObj/Polynomial.hs NumericPrelude: Polynomials]
* [[Add Polynomials]]
+
* [[Add polynomials]]
 
* Solve differential equations in terms of [http://www.haskell.org/pipermail/haskell-cafe/2004-May/006192.html power series].
 
* Solve differential equations in terms of [http://www.haskell.org/pipermail/haskell-cafe/2004-May/006192.html power series].
   

Revision as of 01:24, 7 October 2011

Useful Idioms that will blow your mind (unless you already know them :)

This collection is supposed to be comprised of short, useful, cool, magical examples, which should incite the reader's curiosity and (hopefully) lead him to a deeper understanding of advanced Haskell concepts. At a later time I might add explanations to the more obscure solutions. I've also started providing several alternatives to give more insight into the interrelations of solutions.

More examples are always welcome, especially "obscure" monadic ones.


List/String operations

  -- split at whitespace
  -- "hello world" -> ["hello","world"]
  words

  unfoldr (\b -> fmap (const . (second $ drop 1) . break (==' ') $ b) . listToMaybe $ b)

  takeWhile (not . null) . evalState (repeatM $ modify (drop 1) >> State (break (== ' '))) . (' ' :)
    where repeatM = sequence . repeat

  fix (\f l -> if null l then [] else let (s,e) = break (==' ') l in s:f (drop 1 e))


  -- splitting in two (alternating)
  -- "1234567" -> ("1357", "246")
  -- the lazy match with ~ is necessary for efficiency, especially enabling processing of infinite lists
  foldr (\a ~(x,y) -> (a:y,x)) ([],[])

  (map snd *** map snd) . partition (even . fst) . zip [0..]

  transpose . unfoldr (\a -> toMaybe (null a) (splitAt 2 a))
  -- this one uses the solution to the next problem in a nice way :)
  
  toMaybe b x = if b then Just x else Nothing
  -- or generalize it:
  -- toMaybe = (toMonadPlus :: Bool -> a -> Maybe a)
  toMonadPlus b x = guard b >> return x

  -- splitting into lists of length N
  -- "1234567" -> ["12", "34", "56", "7"]
  unfoldr (\a -> toMaybe (not $ null a) (splitAt 2 a))

  takeWhile (not . null) . unfoldr (Just . splitAt 2)

  ensure :: MonadPlus m => (a -> Bool) -> a -> m a
  ensure p x = guard (p x) >> return x
  unfoldr (ensure (not . null . fst) . splitAt 2)
                 

  -- sorting by a custom function
  -- length -> ["abc", "ab", "a"] -> ["a", "ab", "abc"]
  comparing f = compare `on` f -- "comparing" is already defined in Data.Ord
  sortBy (comparing length)

  map snd . sortBy (comparing fst) . map (length &&& id) 
  -- the so called "Schwartzian Transform" for computationally more expensive 
  -- functions.

  -- comparing adjacent elements
  rises xs = zipWith (<) xs (tail xs)
  
  -- lazy substring search
  -- "ell" -> "hello" -> True
  substr a b = any (a `isPrefixOf`) $ tails b

  -- multiple splitAt's:
  -- splitAts [2,5,0,3] [1..15] == [[1,2],[3,4,5,6,7],[],[8,9,10],[11,12,13,14,15]]
  splitAts = foldr (\n r -> splitAt n >>> second r >>> uncurry (:)) return

  -- frequency distribution
  -- "abracadabra" -> fromList [('a',5),('b',2),('c',1),('d',1),('r',2)]
  import Data.Map
  histogram = fromListWith (+) . (`zip` repeat 1)

  -- using arrows and sort
  histogramArr = map (head&&&length) . group . sort

  -- multidimensional zipWith
  zip2DWith :: (a -> b -> c) -> [[a]] -> [[b]] -> [[c]]
  zip2DWith = zipWith . zipWith
  zip3DWith :: (a -> b -> c) -> [[[a]]] -> [[[b]]] -> [[[c]]]
  zip3DWith = zipWith . zipWith . zipWith
  -- etc.

Mathematical sequences, etc

  -- factorial
  -- 6 -> 720
  product [1..6]

  foldl1 (*) [1..6]   -- this won't work for 0; use "foldl (*) 1 [1..n]" instead

  (!!6) $ scanl (*) 1 [1..]

  fix (\f n -> if n <= 0 then 1 else n * f (n-1))


  -- powers of two sequence
  iterate (*2) 1

  unfoldr (\z -> Just (z,2*z)) 1


  -- fibonacci sequence
  unfoldr (\(f1,f2) -> Just (f1,(f2,f1+f2))) (0,1)

  fibs = 0:1:zipWith (+) fibs (tail fibs)

  fib = 0:scanl (+) 1 fib -- also seen as: fibs = fix ((0:) . scanl (+) 1)


  -- pascal triangle
  pascal = iterate (\row -> zipWith (+) ([0] ++ row) (row ++ [0])) [1]


  -- prime numbers
  -- example of a memoising caf (??)
  primes = sieve [2..] where
           sieve (p:x) = p : sieve [ n | n <- x, n `mod` p > 0 ]

  unfoldr  sieve [2..] where 
           sieve (p:x) = Just(p,   [ n | n <- x, n `mod` p > 0 ])

  otherPrimes = nubBy (((>1).).gcd) [2..]

  -- or if you want to use the Sieve of Eratosthenes..
  diff [] l = l
  diff l [] = l
  diff xl@(x:xs) yl@(y:ys) | x < y     = x:diff xs yl
                           | x > y     = diff xl ys
                           | otherwise = diff xs ys 
  esieve [] = []
  esieve (p:ps) = p:esieve (diff ps (iterate (+p) p))
  eprimes = esieve [2..]

  -- enumerating the rationals (see [1])
  rats :: [Rational]
  rats = iterate next 1 where
       next x = recip (fromInteger n+1-y) where (n,y) = properFraction x

  -- another way
  rats2 = fix ((1:) . (>>= \x -> [1+x, 1/(1+x)])) :: [Rational]

[1] Gibbons, Lest, Bird - Enumerating the Rationals

Monad magic

The list monad can be used for some amazing Prolog-ish search problems.

  -- all combinations of a list of lists.
  -- these solutions are all pretty much equivalent in that they run
  -- in the List Monad. the "sequence" solution has the advantage of
  -- scaling to N sublists.
  -- "12" -> "45" -> ["14", "15", "24", "25"]
  sequence ["12", "45"]

  [[x,y] | x <- "12", y <- "45"]

  do { x <- "12"; y <- "45"; return [x,y] }

  "12" >>= \a -> "45" >>= \b -> return [a,b]

  -- all combinations of letters
  (inits . repeat) ['a'..'z'] >>= sequence

  -- apply a list of functions to an argument
  -- even -> odd -> 4 -> [True,False]
  map ($4) [even,odd]

  sequence [even,odd] 4

  -- all subsequences of a sequence/ aka powerset.
  filterM (const [True, False])

  -- apply a function to two other function the same argument
  --   (lifting to the Function Monad (->))
  -- even 4 && odd 4 -> False
  liftM2 (&&) even odd 4

  liftM2 (>>) putStrLn return "hello"

  fix ((1:) . (>>= \x -> [x+1, 1/(x+1)])) :: [Rational]
  [1%1,2%1,1%2,3%1,1%3,3%2,2%3,4%1,1%4,4%3,3%4,5%2,2%5,5%3,3%5,5%1,1%5,5%4,4%5...
  
  -- forward function concatenation
  (*3) >>> (+1) $ 2

  foldl1 (flip (.)) [(+1),(*2)] 500


  -- perform functions in/on a monad, lifting
  fmap (+2) (Just 2)

  liftM2 (+) (Just 4) (Just 2)


  -- [still to categorize]
  (id >>= (+) >>= (+) >>= (+)) 3        -- 3+3+3+3 = 12
                                        -- Note: need to import Control.Monad.Instances


  -- Galloping horsemen
  -- A large circular track has only one place where horsemen can pass;
  -- many can pass at once there.  Is it possible for nine horsemen to
  -- gallop around it continuously, all at different constant speeds?
  -- the following prints out possible speeds for 2 or more horsemen.
  spd s = ' ': show s ++ '/': show (s+1)
  ext (c,l) = [(tails.filter(\b->a*(a+1)`mod`(b-a)==0)$r,a:l) | (a:r)<-c]
  put = putStrLn . ('1':) . concatMap spd . reverse . snd . head
  main = mapM_ put . iterate (>>= ext) $ [(map reverse $ inits [1..],[])]

  -- output:
  1 1/2
  1 2/3 1/2
  1 3/4 2/3 1/2
  1 5/6 4/5 3/4 2/3
  1 12/13 11/12 10/11 9/10 8/9
  1 27/28 26/27 25/26 24/25 23/24 20/21
  1 63/64 60/61 59/60 57/58 56/57 55/56 54/55
  1 755/756 741/742 740/741 735/736 734/735 728/729 727/728 720/721
  1 126224/126225 122759/122760 122549/122550 122528/122529 122451/122452
    122444/122445 122374/122375 122304/122305 122264/122265


  double = join (+)

  (join . liftM2) (*) (+3) 5            -- (5+3)*(5+3) = 64
                                        -- Note: need to import Control.Monad.Instances

  mapAccumL (\acc n -> (acc+n,acc+n)) 0 [1..10] -- interesting for fac, fib, ...

  do f <- [not, not]; d <- [True, False]; return (f d) -- [False,True,False,True]

  do { Just x <- [Nothing, Just 5, Nothing, Just 6, Just 7, Nothing]; return x }

Other

  -- simulating lisp's cond
  case () of () | 1 > 2     -> True
                | 3 < 4     -> False
                | otherwise -> True

  --or:
  cond = foldr (uncurry if')     -- see [1] below

  -- match a constructor
  -- this is better than applying all the arguments, because this way the
  -- data type can be changed without touching the code (ideally).
  case a of Just{} -> True
            _      -> False


  -- spreadsheet magic
  -- requires import Control.Monad.Instances
  let loeb x = fmap ($ loeb x) x in 
  loeb [ (!!5), const 3, liftM2 (+) (!!0) (!!1), (*2) . (!!2), length, const 17]


  {- 
  TODO, IDEAS:
    more fun with monad, monadPlus (liftM, ap, guard, when)
    fun with arrows (second, first, &&&, ***)
    liftM, ap
    lazy search (searching as traversal of lazy structures)
    innovative data types (i.e. having fun with Maybe sequencing)
  
  LINKS:
    bananas, envelopes, ...   (generic traversal)
    why functional fp matters (lazy search, ...)
  -}

[1]: see Case and If-then-else.

Polynomials

In abstract algebra you learn that polynomials can be used the same way integers are used given the right assumptions about their coefficients and roots. Specifically, polynomials support addition, subtraction, multiplication and sometimes division. It also turns out that one way to think of polynomials is that they are just lists of numbers (their coefficients).

 instance Num a => Num [a] where               -- (1)
   (f:fs) + (g:gs) = f+g : fs+gs               -- (2)
   fs + [] = fs                                -- (3a)
   [] + gs = gs                                -- (3b)
   (f:fs) * (g:gs) = f*g : [f]*gs + fs*(g:gs)  -- (4)
   _ * _ = []                                  -- (5)
   abs           = undefined   -- I can't think of a sensible definition
   signum        = map signum
   fromInteger n = [fromInteger n]
   negate        = map (\x -> -x)

Explanation

(1) puts lists into type class Num, the class to which operators + and * belong, provided the list elements are in class Num.

Lists are ordered by increasing powers. Thus f:fs means f+x*fs in algebraic notation. (2) and (4) follow from these algebraic identities:

 (f+x*fs) + (g+x*gs) = f+g + x*(fs+gs)
 (f+x*fs) * (g+x*gs) = f*g + x*(f*gs + fs*(g+x*gs))

(3) and (5) handle list ends.

The bracketed [f] in (4) avoids mixed arithmetic, which Haskell doesn't support.

Comments

The methods are qualitatively different from ordinary array-based methods; there is no vestige of subscripting or counting of terms.

The methods are suitable for on-line computation. Only n terms of each input must be seen before the n-th term of output is produced.

Thus the methods work on infinite series as well as polynomials.

Integer power comes for free. This example tests the cubing of (1+x):

  [1, 1]^3 == [1, 3, 3, 1]


This gives us the infinite list of rows of Pascal's triangle:

   pascal = map ([1,1]^) [0..]

For example,

   take 5 pascal -- [[1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1]]

See also