Some Examples

 foo1 text = unlines (map reverse (lines text))

Will this definition pass the type checker? What is its type? Given that lines :: String -> [String] and unlines :: [String] -> String, then it can infer that text should be a String, can approve the use of map, and can conclude that the result is going to be a String—in other words, conclude foo1 :: String -> String. No programmer annotations are needed, and our safety net has passed the code for use.

Let’s try some type-driven development now. Suppose I want a function group_on that works a bit like Ruby’s group_by—for example, where (1..10).group_by {|x| x % 2 == 0 } gives {false=>[1, 3, 5, 7, 9], true=>[2, 4, 6, 8, 10]}. For the sake of making the example a bit more complex, ...

Get Functional Programming: A PragPub Anthology now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.