Skip to content

Instantly share code, notes, and snippets.

@bryanwoods
Created January 14, 2014 18:33
Show Gist options
  • Save bryanwoods/8423251 to your computer and use it in GitHub Desktop.
Save bryanwoods/8423251 to your computer and use it in GitHub Desktop.
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