开发者

Why does the following simple Haskell function give slightly strange answers?

(%?) :: 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开发者_JS百科 %? \z -> z * 2 %? \z -> z + 3

e.g, p 4 = 20


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.


%? 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 $.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜