开发者

How is partial application working here?

开发者 https://www.devze.com 2023-01-23 15:45 出处:网络
> map (++ \"!\") [\"a\", \"b\", \"c\"] [\"a!\",\"b!\",\"c!\"] > (++) \"!\" \"a\" \"!a\" These two lines don\'t make sense to me. When using ++ in map, it seems like the first parameter is appe
> map (++ "!") ["a", "b", "c"]
["a!","b!","c!"]
> (++) "!" "a"
"!a"

These two lines don't make sense to me. When using ++ in map, it seems like the first parameter is appended to the second, but in the second list it's the other way around. How does Haskell reason about the behavio开发者_如何学JAVAr in the map function?


The (++ "!") is a bit of special syntax called an operator section. It's partially-applying the second parameter of the infix operator, whereas (++) "!" works like normal partial application and is applying the first parameter.

You can also do the same thing with regular functions used infix-style with backticks: (`map` [1..3]) is equivalent to (\f -> map f [1..3]).

It seems odd because it is, it's a special-case extra feature that's in there just because it's darn useful.


The partial application (++ "!") is identical to (\x -> x ++ "!"). In other words, the expression (++ "!") is smart enough to know that the "!" is the second argument to (++). It knows this because it knows that ++ is an infix operator. In the second expression, (++) "!" "a" is identical to "!" ++ "a", and does what you'd expect.


map (++ "!) ["a", "b", "c"]

is equivalent to

["a" ++ "!", "b" ++ "!", "c" ++ "!"]

And

(++) "!" "a"

is equivalent to

"!" ++ "a"

Hope this helps.

0

精彩评论

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