Exercise 5.4


Assume that f2 = map.
Then:

f1 :: [a -> a] -> a -> [a]
f1 fs x = map (\f -> f x) fs

Or in one line:

(\fs x -> map (\f -> f x) fs) (map (*) [1,2,3,4]) 5 => [5,10,15,20]

8 responses to “Exercise 5.4”

  1. You could eliminate the lambda expression in the definition of f1 as follows:

    f1 fs x = map ($ x) fs

    I don’t know whether it’s good form or not–I’m new at this. But it seems to work.

  2. Of course, that is much better.

    Also, technical error 11 on the errata page mentions a solution involving map, flip and ($). Presumably the usage of flip would enable making f1 a curried function, although I haven’t worked this out.

  3. Elucidation from Paul Hudak himself:

    What we need is an “applyToEach” function for f1, such as:

    f1 [] x = []
    f1 (g:gs) x = g x : f gs x

    Note that if we reverse the two arguments to f1:

    f1 x [] = []
    f1 x (g:gs) = g x : f gs x

    then f1 can be rewritten as:

    f1 x gs = map ($x) gs

    which can be simplified to:

    f1 x = map ($x)

    and furthermore can be written completely “point-free” by noting that:

    map ($x) = map (\f-> f x) = map ((\x \f -> f x) x) = map (flip ($) x) = (map . flip ($)) x

    which leads to:

    f1 = map . flip ($)

    So now the whole thing can be written:

    flip (map . flip ($)) (map (*) [1,2,3,4]) 5

  4. I’m a beginner, but I know a bit about partial application, currying, using flip, lambda expressions, etc, from reading in other texts. I’m confused why these problems (5.2 through 5.4) come so early in the book, before he has introduced any of these techniques. I tried to solve them to no avail using only what had been introduced so far.

  5. I’m a beginner, and was not obvious that map can be used with a function that takes more than one argument. Using what has been in the text so far, and also without using map for f2

    f2 op [] = []
    f2 op (x:xs) = (x, op) : f2 op xs
    
    f1 [] a = []
    f1 ((b, op):xs) a = (b `op` a) : f1 xs a
    
  6. Thanks Mike,

    I also think that those exercises are misplaced.
    By the way, I found a “mapped” way of your solution:

    f2 op xs = map f xs where f x = (x,op)
    f1 xs a = map f xs where f (b,op) = a `op` b

  7. It is worth noting that in my version of the book (10th printing 2008), this exercise is missing and all following in this chaper move on up. Took my while to figure it out, since the solution was looking nothing like my try 😉

  8. I think the author expected us to determine that f1 = sequence and f2 = map:

    sequence (map (*) [1..4]) 5

Leave a Reply

Your email address will not be published. Required fields are marked *