haskell-classes/2016-03-07.md

2.7 KiB

Day 5

  • Homework from day 4
  • Higher order programming
    • Anonymous functions

λ> let f = \x y -> x `div` y

  • Function composition
λ> let isEvenLengthTree t = even (length (inOrder t))
λ> let compose f g = \x -> f (g x)
λ> :t compose
compose :: (b -> c) -> (a -> b) -> a -> c
λ> let isEvenLengthTree t = (even `compose` length `compose` inOrder) t
λ> :t isEvenLengthTree
isEvenLengthTree :: BST -> Bool
λ> :t (.)
(.) :: (b -> c) -> (a -> b) -> a -> c
λ> let isEvenLengthTree t = (even . length . inOrder) t
λ> :t ($)
($) :: (a -> b) -> a -> b
λ> length $ [1..10]
10
λ> :i ($)
($) :: (a -> b) -> a -> b 	-- Defined in GHC.Base’
infixr 0 $
λ> let isEvenLengthTree t = even . length . inOrder $ t
λ> :t isEvenLengthTree
isEvenLengthTree :: BST -> Bool
  • Currying
  • Partial application
λ> let t = fromList [1..10]
λ> :t insert t
insert t :: Int -> BST
λ> let insertIntoT = insert t
λ> t
Node (Node (Node (Node (Node (Node (Node (Node (Node (Node EmptyNode 1 EmptyNode) 2 EmptyNode) 3 EmptyNode) 4 EmptyNode) 5 EmptyNode) 6 EmptyNode) 7 EmptyNode) 8 EmptyNode) 9 EmptyNode) 10 EmptyNode
λ> insertIntoT 30
Node (Node (Node (Node (Node (Node (Node (Node (Node (Node EmptyNode 1 EmptyNode) 2 EmptyNode) 3 EmptyNode) 4 EmptyNode) 5 EmptyNode) 6 EmptyNode) 7 EmptyNode) 8 EmptyNode) 9 EmptyNode) 10 (Node EmptyNode 30 EmptyNode)
λ> insertIntoT (-30)
Node (Node (Node (Node (Node (Node (Node (Node (Node (Node (Node EmptyNode (-30) EmptyNode) 1 EmptyNode) 2 EmptyNode) 3 EmptyNode) 4 EmptyNode) 5 EmptyNode) 6 EmptyNode) 7 EmptyNode) 8 EmptyNode) 9 EmptyNode) 10 EmptyNode
λ> :t insertIntoT
insertIntoT :: Int -> BST
λ> :t uncurry
uncurry :: (a -> b -> c) -> (a, b) -> c
λ> :t uncurry insert
uncurry insert :: (BST, Int) -> BST
λ> :t curry . uncurry $ insert
curry . uncurry $ insert :: BST -> Int -> BST
λ> (find 99 (insert 4 (fromList [1..10])))
False
λ> find 99 . insert 4 . fromList $ [1..10]
False
λ> find 99 $ insert 4 $ fromList $ [1..10]
False
λ> let f = find 99 . insert 4 . fromList
λ> f [1..10]
False
λ> :t flip
flip :: (a -> b -> c) -> b -> a -> c
λ> :t find
find :: Int -> BST -> Bool
λ> :t flip find
flip find :: BST -> Int -> Bool
λ> :m +Data.Function
λ> :t (&)
(&) :: a -> (a -> b) -> b
λ> [1..10] & fromList & insert 4 & find 99
False
λ> let f |> g = \x -> g . f $ x
λ> let f = fromList |> insert 4 |> find 99
λ> :t (|>)
(|>) :: (r -> b) -> (b -> c) -> r -> c
λ>  [1..1] & fromList |> insert 4 |> find 99
False
λ> fromList |> insert 4 |> find 99 $ [1..10]
False
λ> fromList |> (find 99 . insert 4) $ [1..10]
False

Homework: write these functions

  • map :: (a -> b) -> [a] -> [b]
  • filter :: (a -> Bool) -> [a] -> [a]
  • fold :: (r -> a -> r) -> r -> [a] -> r