Difference between revisions of "Instances of List and Maybe"

From HaskellWiki
Jump to navigation Jump to search
(Class instances of list)
 
Line 41: Line 41:
   
 
<haskell>
 
<haskell>
> (\lst -> do x<-lst; return (x*x)) [1,2,3]
+
> (\ lst1 lst2 -> do x<-lst1; y<-lst2; return (x*y)) [1,2] [3,4]
[1,4,9]
+
[3,4,6,8]
 
</haskell>
 
</haskell>
   

Revision as of 14:07, 20 June 2018

This pages lists all class instances of List in base, with examples of use. You can run the examples in GHCi.

Semigroup

> import Data.Semigroup
> [1,2] <> [3,4]
[1,2,3,4]

Monoid

> [] == mempty
True

Functor

> fmap (+1) [2, 3]
[3, 4]

Applicative

> [(+1),(+2)] <*> [3,4]
[4,5,5,6]

Alternative

> import Control.Applicative
> [1] <|> empty <|> [2]
[1,2]

Monad

> (\ lst1 lst2 -> do x<-lst1; y<-lst2; return (x*y)) [1,2] [3,4]
[3,4,6,8]

MonadPlus

> import Control.Monad
> (\lst -> do x<-lst; guard (x*x<5); return (x*x)) [1,2,3]
[1,4]

Foldable

> foldr (+) 0 [1,2]
3

Traversable

> traverse (\x -> [0..x]) [0..2]
[[0,0,0],[0,0,1],[0,0,2],[0,1,0],[0,1,1],[0,1,2]]
> sequenceA [[1,2],[3,4]]
[[1,3],[1,4],[2,3],[2,4]]