Notes from the session on Friday, 2016-09-16

Avoid the tab character in Haskell source files

Different editors treat tabs differently, and whitespace (measured as numbers of whitespace characters) is syntactically meaningful in Haskell.

Therefore it is a bad idea to insert tabs in a source file. Use a text editor that inserts a number of whitespace characters when you hit the tab key. (Or better: learn how to instruct your text editor to do so.)

Note that [x]++xs can always be replaced by x:xs.

Note that \ x -> f x can always be replaced by f.

Note that \ x y -> f y x can always be replaced by flip f.

So instead of \ ys x -> x:ys one can say flip (:).

Instead of

    \ _ x -> succ x

one can always write

    \ _ -> succ

or even

    const succ                   

Folding right and folding left

We talked about foldr versus foldl. One way to see the difference is by giving the parameters mnemonic names, as follows.

  foldr (\todo \done -> ... ) stop

  foldl (\done \todo -> ... ) start

This way of naming the parameters makes clear that foldr stops when the end of the list is reached. If the operation on todo and done only involves todo, then foldr can be called lazily, and hence foldr can be used to operate on infinite lists.

Lazily calling foldl on an infinite list does not work, for foldl only starts when the end of the list is reached.

Example of using getLine and readLn

> main :: IO ()
> main = do
>   putStr "Your First Name: "
>   fname <- getLine
>   putStr "Your Last Name: "
>   lname <- getLine
>   putStr "Your age: "
>   age <- readLn -- 
>   putStrLn $ greeting fname lname age

Note that getLine gives us a String, while readLn will convert the user input to something of a type in the Read type class. Here this is Int because we use age as the third argument to greeting:

> greeting :: String -> String -> Int -> String
> greeting fname lname age =
>   "Hello, " ++ fname ++ " " ++ lname ++ " (" ++ show age ++ ")!"