tags:

views:

144

answers:

2
(%?) :: Int -> (Int -> Int) -> Int
x %? f = f x

m :: Int -> Int
m v = v %? \z -> z * 2 %? \z -> z + 3 %? \x -> x + z

or simpler

p :: Int -> Int
p v = v %? \z -> z * 2 %? \z -> z + 3

e.g, p 4 = 20

A: 

%? has too high precedence and is left-associative, so v %? \z -> z * 2 %? \z -> z + 3 is the same as v %? \z -> z * (2 %? \z -> z + 3).

If you want %? to behave like $ use infixr 0 %?, so it has the same precedence and associativity as $.

sepp2k
that was pretty fast, thanks!
+1  A: 

Well, it would help to know what you were expecting it to do. But perhaps it would help to put some explicit parentheses in p:

q :: Int -> Int
q v = v %? (\z -> z * (2 %? (\z -> z + 3)))

Perhaps you were you expecting something more like this:

p2 :: Int -> Int
p2 v = v %? (\z -> (z * 2) %? (\z -> z + 3))

It's probably a good idea to add an infix declaration for any operators you declare, to avoid this sort of confusion. Arithmetic operators have mid-high precedence, but given what the function does you probably want very low precedence anyway.

As an aside--lambdas extend all the way to the right, but I'm guessing that's not what's tripping you up.

camccann
great work, thanks!