Skip to content

Instantly share code, notes, and snippets.

@gabebw
Last active August 29, 2015 14:25
Show Gist options
  • Save gabebw/56e4691da260b83387e6 to your computer and use it in GitHub Desktop.
Save gabebw/56e4691da260b83387e6 to your computer and use it in GitHub Desktop.

Ch 1: Basics

GHCI

  • :l baby to load baby.hs
  • :t (+) to show function type
    • parentheses required for infix functions
  • * is an infix function (because it's punctuation)
    • so 5 * 3 is parsed exactly as * 5 3, which is really (* 5) 3

Lists

  • [1] ++ [3]
  • 1:[3]
  • homogeneous: List a

Tuple

  • unlike lists, heterogeneous: (a, b); (a, b, c)

List comprehensions

let rightTriangles = [ (a,b,c) | c <- [1..10], b <- [1..c], a <- [1..b], a^2 + b^2 == c^2]

Hoogle

  • helpful
  • but you should know types
    • e.g. search [a] to find list functions
    • search (a, b) to find tuple functions
    • Data.x is a good marker for base data type functions

Ch 3: Typeclasses

http://learnyouahaskell.com/types-and-typeclasses

  • Eq a
  • show/read

Ch 4: Function Syntax

  • Pattern matching!!! wow
    • interestingly, syntax sugar for case expressions
  • Guards
  • Can use _ as fallback to indicate we don't care
  • otherwise is literally equivalent to True
  • where to define private sub-functions
    • but often better as their own function
  • let...in, but I barely use that
lucky :: (Integral a) => a -> String
lucky 7 = "LUCKY NUMBER SEVEN!"
lucky x = "Sorry, you're out of luck, pal!"

first :: (a, b, c) -> a
first (x, _, _) = x

-- The (x:xs) makes sense, I promise
-- It's the same as `1:[3]` above
-- Note that `head' [1..]` works! Doesn't spin forever.
head' :: [a] -> a
head' (x:xs) = x

-- case
head'' :: [a] -> a
head'' xs = case xs of [] -> error "No head for empty lists!"
                       (x:_) -> x

Settings

Extras

Homework

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment