Haskell for Scala-ists

Preview:

Citation preview

Haskell for Scala-istsChris Eidhof

Three things

• Datatypes

• Purity

• Laziness

List

• data [a] = [] | a : [a]

Type

Type-parameter

Constructor

Constructor

Case distinction

Functions

• reverse :: [a] -> [a]

• reverse [] = []

• reverse (x:xs) = reverse xs ++ [x]

Give me a list of a And I’ll return alist of a

Pattern Matching

Purity

• State = Evil

Purity

• Same Input

• =

• Same output

Referential

Transparency

Purity

• No side effects:

• * Variables / Mutable state

• * I/O

• * launchMissiles()

Example

• sort :: [Int] -> [Int]

How do we know sort doesn’t launch missiles?

• putStrLn :: String -> IO ()

The IO type shows us it’s not pure

Doing I/O

Doing I/O

(>>=) :: IO a -> (a -> IO b) -> IO b

main = putStrLn "hello! what's your name?" >>= \() -> getLine >>= \name -> putStrLn ("hello, " ++ name)

Doing I/O

main = do putStrLn "hello! what's your name?" name <- getLine putStrLn ("hello, " ++ name)

Fusion

• myFunction = map square . map toInt

• = map (square . toInt)

Quickcheck

• Automatic testing of pure code.

Parallel code

• map  :: (a -> b) -> [a] -> [b]

• parMap :: (a -> b) -> [a] -> [b]

Composability

• Pure code is easy to compose, it is

• * Stateless

• * Self-contained

Effects

Dangerous SafeUseless

UsefulMost

languages

Haskell

Nirvana

Simon Peyton-Jones, Caging The Effects Monster

Laziness

• if (x < 10 && x > 5)

Laziness: Quicksort

qsort [] = []qsort (x:xs) = qsort (filter (< x) xs) ++ [x] ++ qsort (filter (>= x) xs)

minimum ls = head (quickSort ls)

Read more

• Real World Haskell - http://book.realworldhaskell.org/

• Haskell.org - http://haskell.org

• Haskell Café - http://haskell.org/haskellwiki/Mailing_lists

• Planet Haskell - http://planet.haskell.org/

• Haskell reddit - http://haskell.reddit.com

Keep in touch

• http://github.com/chriseidhof

• @chriseidhof

Recommended