Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Partial function application with List.map

Tags:

f#

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?

like image 836
Maik Klein Avatar asked Dec 21 '13 14:12

Maik Klein


2 Answers

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.

like image 181
Tarmil Avatar answered Sep 21 '22 01:09

Tarmil


You need to put brackets around the +:

List.map ((+)1) [1..10]
like image 28
Lee Avatar answered Sep 21 '22 01:09

Lee