5

I am currently reading Programming in F# 3.0 and I read that F# supports partial function application.

But if I try

List.map (+1) [1 .. 10];;

Then I get error FS0001: This expression was expected to have type 'a -> 'b

but List.map (fun x -> x + 1) [1 .. 10];; compiles fine. Any ideas why?

Maik Klein
  • 15,548
  • 27
  • 101
  • 197

2 Answers2

7

I suppose you come from Haskell, for expecting it to work this way :)

Unfortunately, F# doesn't have the syntactic sugar where you can partially apply an operator by parenthesizing it preceded or followed by an expression. In your code, +1 is considered a single number token, which is why it complains that it is not a function.

What F# does have, however, is the syntax where you can parenthesize the operator alone. Which leads to @Lee's solution. Be careful about this syntax though: (+) 1 is equivalent to Haskell's (1+), not (+1). Obviously for addition it doesn't matter, but for asymmetrical operations such as subtraction, it can be misleading.

Tarmil
  • 11,177
  • 30
  • 35
  • Yes for me it is quite obvious that if I would write `add x` or `(+) 1` that it would be the left side. But if I want to really express `+1` I would have to use a lambda? like `fun x -> x + 1`? – Maik Klein Dec 21 '13 at 15:57
  • 1
    @MaikKlein, you have to pass a function, but `+1` is not a function expression; `(+) 1` is. Many suggest that lambda has the most readable syntax, especially because of non-symmetric operators. If you write `(/) 2`, it would be `fun x -> 2 / x`, which is confusing. However, it is possible to write it in a point-free style. `fun x -> x / 2` is equivalent to `(/) >> (|>) 2`. See [this answer](http://stackoverflow.com/a/11383421/974789). – Be Brave Be Like Ukraine Dec 21 '13 at 16:12
  • @MaikKlein The basic problem is that how do differentiate `+1=1` from `+1=fun x -> x+1`. The F# solution is that you are always trying to write a number rather than a function. – John Palmer Dec 21 '13 at 21:04
5

You need to put brackets around the +:

List.map ((+)1) [1..10]
Lee
  • 142,018
  • 20
  • 234
  • 287