Instances of List and Maybe

From HaskellWiki
Jump to navigation Jump to search

This pages compares the Typeclassopedia classes of List and Maybe, with examples of use. You can run the examples in GHCi.

Semigroup
List Maybe
> import Data.Semigroup
> [1,2] <> [3,4]
[1,2,3,4]
> import Data.Semigroup
> (Just [1,2]) <> (Just [3,4])
Just [1,2,3,4]


Monoid
List Maybe
> mempty :: [Int]
[]
> [1,2] <> mempty
[1,2]
> mempty :: Maybe [Int]
Nothing
> (Just [1,2]) <> mempty
Just [1,2]


Functor
List Maybe
> fmap (+1) [2, 3]
[3, 4]
> fmap (+1) []
[]
> fmap (+1) (Just 2)
Just 3
> fmap (+1) Nothing
Nothing


Applicative
List Maybe
> [(+1),(+2)] <*> [3,4]
[4,5,5,6]
> [] <*> [3,4]
[]
> (Just (+1)) <*> (Just 2)
Just 3
> Nothing <*> (Just 2)
Nothing


Alternative
List Maybe
> import Control.Applicative
> [1] <|> empty <|> [2]
[1,2]
> empty <|> [2]
[2]
> import Control.Applicative
> (Just 1) <|> empty <|> (Just 2)
Just 1
> Nothing <|> (Just 2)
Just 2


Monad
List Maybe
> mul xs ys = do x<-xs; y<-ys; return (x*y)
> mul [1,2] [3,4,5]
[3,4,5,6,8,10]
> mul x' y' = do x<-x'; y<-y' return (x*y)
> mul (Just 2) (Just 5)
Just 10


MonadPlus
List Maybe
> import Control.Monad
> squares5 x' = do x<-x'; guard (x*x<5); return (x*x)
> squares5 [1,2,3]
[1,4]
> squares5 []
[]
> import Control.Monad
> squares5 x' = do x<-x'; guard (x*x<5); return (x*x)
> squares5 (Just 2)
Just 4
> squares5 (Just 3)
Nothing
> squares5 Nothing
Nothing


Foldable
List Maybe
> foldr (+) 0 [1,2]
3
> foldr (+) 1 (Just 2)
3


Traversable
List Maybe
> 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]]
> traverse (\x -> [x, x*x]) (Just 3)
[Just 3,Just 9]
> sequenceA [Just 3, Just 4]
Just [3,4]
> sequenceA [Just 3, Nothing]
Nothing
> sequenceA (Just [3,4])
[Just 3,Just 4]


To do : MonadFix