Created
February 20, 2023 09:59
-
-
Save takanuva/4eebf715eb8f82bf808712ab3fdab90d to your computer and use it in GitHub Desktop.
Functional Programming - Class 6
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
foo = Just (not True) | |
bar = Just not | |
-- not :: Bool -> Bool | |
-- Just :: a -> Maybe a | |
-- Just not :: Maybe (Bool -> Bool) | |
-- | |
baz = Just . not | |
-- Remember that the dot operator joins two functions | |
-- and creates a new one! | |
-- (.) :: (b -> c) -> (a -> b) -> a -> c | |
-- | |
{- | |
Whenever I see "a b c", it means: | |
- [x] (a b) c | |
- [ ] a (b c) | |
-} | |
funcs :: [Integer -> Integer] | |
funcs = [\x -> x + 1, \y -> 0, \x -> x * 2] | |
map' :: (a -> b) -> [a] -> [b] | |
map' f [] = -- (1) | |
[] | |
map' f (x:xs) = -- (2) | |
f x : map' f xs | |
res = map' (\f -> f 10) funcs | |
{- | |
res = | |
map' (\f -> f 10) funcs = | |
map' (\f -> f 10) [\x -> x + 1, \y -> 0, \x -> x * 2] = | |
(\f -> f 10) (\x -> x + 1) : map' ... ... = | |
^^^^^^^^^^^^^^^^^^^^^^^^^^ | |
(\x -> x + 1) 10 : map' ... ... = | |
^^^^^^^^^^^^^^^^ | |
10 + 1 : map' ... ... = | |
11 : map' ... ... = | |
11 : 0 : 20 | |
map' (\f -> f 10) [\x -> x + 1, \y -> 0, \x -> x * 2] = | |
I am just adding the function (\f -> f 10) before every item! | |
[(\f -> f 10) (\x -> x + 1), | |
(\f -> f 10) (\y -> 0), | |
(\f -> f 10) (\x -> x * 2)] = | |
And the function says we call each item with 10 as input! | |
[(\x -> x + 1) 10, | |
(\y -> 0) 10, | |
(\x -> x * 2) 10] = | |
-} | |
{- | |
Recall the Either datatype, which allows us to have two different | |
types together! | |
- Left :: a -> Either a b | |
- Right :: b -> Either a b | |
-} | |
example = [Left 42, Right 'h', Right 'i', Left 100] | |
-- Left 42 :: Either Integer b | |
-- Right 'h' :: Either a Char | |
-- So, example :: [Either Integer Char] | |
{- | |
What's the type of map Left? | |
map :: (a -> b) -> [a] -> [b] | |
Left :: c -> Either c d | |
I'm giving Left as input to map, so Haskell will try to match the types! | |
(a -> b) = c -> Either c d | |
We're allowed to replace variables, so we take a = c, and b = Either c d! | |
Since we have this replacement working, we'll apply that to the result! | |
We want [a] -> [b] with a = c and b = Either c d, so: | |
So map Left :: [c] -> [Either c d] | |
= [a] -> [Either a b] | |
-} | |
-- data Maybe a = Just a | Nothing | |
safeHead :: [a] -> Either String a | |
safeHead [] = | |
Left "the list was empty!" | |
safeHead (x:xs) = | |
Right x |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment