Posted By: Charles | Nov 12th, 2009 @ 8:42 AM | 42,469 Views | 14 Comments

We've kicked off C9 Lectures with a journey into the world of Functional Programming with functional language purist and high priest of the lambda calculus, Dr. Erik Meijer (you can thank Erik for many of the functional constructs that have shown up in languages like C# and VB.NET. When you use LINQ, thank Erik in addition to Anders). 

We will release a new chapter in this series every Thursday.

In Chapter 7, Dr. Meijer teaches us about Higher-Order Functions. A function is called higher-order if it takes a function as an argument and returns a function as a result:

twice    :: (a -> a) -> a -> a
twice f x = f (f x)

The function twice above is higher order because it takes a function (f x) as it first argument and returns a function (f(fx)) 

Dr. Meijer will elaborate on why higher-order functions are important and there are some really interesting side-effects of higher-order functions such as defining DSLs as collections of higher-order functions and using algebraic properties of higher-order functions to reason about programs.

You should watch these in sequence (or skip around depending on your curent level of knowledge in this domain):

Chapter 1
Chapter 2
Chapter 3
Chapter 4
Chapter 5
Chapter 6

Now, we do have a textbook and you should go buy it: The great Graham Hutton's Programming in Haskell. We worked with the publisher, Cambridge University Press, to get all Niners a 20% discount on the book. Now, you don't need the book to learn a great deal from this lecture series since Graham's website has all the slides and samples from the book as well as answers to the exercises. That said, it's highly recommended reading and you should consider it.

The promotion code is 09HASK and it is vaild on both the Hardback:

9780521871723 and Paperback: 9780521692694. The catalog pages are:

Hardback:

http://www.cambridge.org/us/catalogue/catalogue.asp?isbn=9780521871723 and the paperback is:

http://www.cambridge.org/us/catalogue/catalogue.asp?isbn=9780521692694

Note: This special offer is valid until December 31, 2009

Rating:
10
0

We have reached the halfway point!

The equational reasoning part on the append operator (++) is wrong. This is what Erik wrote:

xs ++ ys = foldr (:) ys xs
≡ { 1 }
(++) ys xs = foldr (:) ys xs
≡ { 2 }
(++) ys = foldr (:) ys
≡ { 3 }
(++ ys) = foldr (:) ys
≡ { 4 }
(++) = foldr (:)


This contains several errors:

  • The first equality is wrong because the arguments are flipped: xs ++ ys ≡ (++) xs ys
  • The second equality is true, although since the arguments of append are flipped, the function doesn't have the correct behaviour
  • The third equality is wrong because it's flipping the arguments again. Although actually, (++ ys) isn't a valid way to define a function, so you can't write this down in Haskell. But if this were valid Haskell, the the behaviour of this append operator would be correct again.
  • The fourth equality is wrong again because it once again flips the arguments.


A correct way to define append would be:

(++) = flip (foldr (:))

 

Having said all that, I really like this series.

 

Keep on going Erik! Smiley

exoteric
exoteric
embarassingly sequential

A function that returns a function? That is clear: It's a curried function!

 

a -> b // function
a -> b -> c // curried function
(a -> b) -> c // but
a -> (b -> c) // vs

 

Apparently, if history be the judge, currying ought to be called Schönfinkeling and curried functions Schönfinkeled functions after the true inventor of this transformation, Moses Schönfinkel. Sad fate: his papers were burned for heating by his neighbors and he ended up in a sanatorium! Maybe currying is safer after all.

I don't think it's wrong at all. He hasn't flipped the arguments, he puts "ys" as the base case for the fold, meaning it will end up "to the right" (hence the "r" in foldr).

 

EDIT: Ah, I see what you mean, I thought you meant the first "=" sign. sorry about that, anyway. I'll keep this here because it's neat.

 

Put this in a Haskell file:


import Test.QuickCheck



prop_Concat :: [Int] -> [Int] -> Bool


prop_Concat xs ys = xs ++ ys == foldr (:) ys xs

 

 

This code defines a quickCheck property, which is a way of automatically generating tests in Haskell. You specify what you expect to be true for the inputs, and it generates tons of data for you and verifies that the property is indeed true.

 

Then open it in GHCi (or hugs, I think) and do:

 

 

 


*Main> quickCheck prop_Concat


OK, passed 100 tests

 

 

 

Right Smiley

 

To be clear to everyone: What I'm saying is that the equalities are wrong. The first definition is perfectly fine.

 

Also sylvan: Very nince demo of QuickCheck, and a good thing you put a type signature on prop_Concat.

When I started using QuickCheck I didn't do that and GHCi defaulted that kind of a function to: prop_Concat :: [()] -> [()] -> Bool

So the tests all ran OK and I ended up submitting a wrong solution to an exercise to my teacher...

Again nice lecture!

 

A comment about implementing takeWhile and dropWhile using foldr. These are functions to take or drop elements at the beginning of a list. So, I think it would be easier to implement them using foldl (fold left). Can it be done with foldr? I’m not sure. The drawback to implement them with fold is that they would be useless when dealing with infinite lists. That is because fold(r|l) consume the whole list before producing a result.

 

Here is my take on both using foldl

takeWhile' :: (a -> Bool) -> [a] -> [a]
takeWhile' p = snd . foldl (\(e,v) x -> if e then (e,v) else if p x then (False,v++[x]) else (True,v)) (False,[])

dropWhile' :: (a -> Bool) -> [a] -> [a]
dropWhile' p = snd . foldl (\(e,v) x -> if e then (e,v++[x]) else if p x then (True,v) else (False,v++[])) (False,[])

 

I'd say its easier to implement takeWhile using foldr:

takeWhile p = foldr (\x xs -> if p x then x : xs else []) []


Also, foldr most definitely does not consume the whole list before producing a result. Take this definition:

foldr :: (a -> b -> b) -> b -> [a] -> b
foldr f z []     = z
foldr f z (x:xs) = f x (foldr f z xs)


As you can see in the cons case; foldr calls f with x and the result of a recursive call.
However, since Haskell is lazy, f gets executed before the result of the recursive call is computed. If f decides to never inspects its second argument, the recursive call will never be evaluated. So that's why you can do: takeWhile (<4) [0..]

 

However, you are right about foldl.

foldl :: (a -> b -> a) -> a -> [b] -> a
foldl f z []     = z
foldl f z (x:xs) = foldl (f z x) xs


foldl first recurses, before executing the f function that produces the result value.

So calling the takeWhile', defined below, with an infinite list will result in an infinite computation.

 

takeWhile' p = foldl (\ys x -> if p x then ys ++ [x] else ys) []

I much prefer this for reverse:

 

reverse = foldl (flip (:)) []

 

The 'foldl' expresses the eagerness required by reverse, and the 'flip (Smiley' expresses the all-pairs transposition.

Microsoft Communities