Created
January 14, 2014 18:33
-
-
Save bryanwoods/8423251 to your computer and use it in GitHub Desktop.
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
import Data.Maybe | |
-- Lazy evaluation | |
natNums = [1..] | |
odds = [1,3..] | |
evens = [2,4..] | |
addXAndY :: Integer | |
addXAndY = sum | |
where x = 1 | |
y = 2 | |
sum = x + y | |
-- Type inference | |
-- ghci repl: | |
-- Prelude> :t natNums | |
-- Prelude> natNums :: [Integer] | |
-- Function composition, partial application, currying | |
inc :: Integer -> Integer | |
-- inc i = i + 1 | |
-- inc = \i -> i + 1 | |
inc = (+1) | |
addOneToSomeOdds :: [Integer] | |
-- map (\x -> inc x) (take 10 odds) | |
-- map (\x -> inc x) $ take 10 odds | |
-- map (inc) $ take 10 odds | |
addOneToSomeOdds = map inc $ take 10 odds | |
-- Pattern Matching | |
greeting :: [Char] -> [Char] | |
greeting name | |
| name == "Bryan" = ("Sup " ++ name) | |
| name == "Abel" = ("Feel like some karoke, " ++ name) | |
| otherwise = "Hey...you" | |
-- Pattern matching, lazy evaluation, recursion | |
quicksort :: Ord a => [a] -> [a] | |
quicksort [] = [] | |
quicksort (x:xs) = quicksort lessThanOrEqual ++ [x] ++ quicksort greaterThan | |
where lessThanOrEqual = filter (<= x) xs | |
greaterThan = filter (> x) xs | |
-- TYPES!!!! | |
data Day = Monday | Tuesday | Wednesday | Thursday | Friday | Saturday | Sunday | |
deriving (Eq, Ord, Show) | |
-- Main> show Monday | |
-- "Monday" | |
-- Main> Friday > Monday | |
-- True | |
-- Main> Friday == Monday | |
-- False | |
-- Main> :t Wednesday | |
-- Wednesday :: Day <-- Types are functions! | |
-- Goodbye null pointers! | |
-- Prelude> tail [] | |
-- *** Exception: Prelude.tail: empty list | |
safeTail :: [a] -> Maybe [a] | |
safeTail [] = Nothing | |
safeTail (_:xs) = Just xs | |
-- *Main Data.Maybe> safeTail [] | |
-- Nothing | |
-- *Main Data.Maybe> take 10 (safeTail odds) | |
fiveFromTail :: Maybe [a] | |
fiveFromTail = case safeTail [] of | |
Just x -> Just (take 5 x) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment