Reputation:
The two expressions below produce the same output:
> ("hello" + " " + "world!");;
val it : string = "hello world!"
> "hello" + " " + "world!";;
val it : string = "hello world!"
Why then String.length
works with the first but not with the second one?
> String.length ("hello" + " " + "world!");;
val it : int = 12
> String.length "hello" + " " + "world!";;
String.length "hello" + " " + "world!";;
------------------------^^^
stdin(57,25): error FS0001: The type 'string' does not match the type 'int'
This was generated on FSI 14.0.22214.0
Upvotes: 0
Views: 3786
Reputation:
This happens because functions bind more strongly than the (+) operator.
> String.length "hello" + " " + "world!"
Evaluates to:
> 5 + " " + "world!"
Which produces the same error:
> 5 + " " + "world!";;
5 + " " + "world!";;
----^^^
stdin(1,5): error FS0001: The type 'string' does not match the type 'int'
Upvotes: 3
Reputation: 109100
The parentheses are overriding the normal operator precedence. In particular function & argument has a very high precedence, so in the latter case it is being evaluated as
(String.length "hello") + " " + "world!"
and then trying to add a number to a string.
Upvotes: 6