Reputation: 241
I want to rewrite this
//finds the max of 3 numbers
let max3 (n1, n2, n3) = let mx1 = if (n1 > n2) then n1 else n2 in if (mx1 > n3) then mx1 else n3;
without using "in"
I came up with this
let max3 (n1, n2, n3) =
let mx1 =
if (n1 > n2)
then n1
else n2
let mx2=
if (mx1 > n3)
then mx1
else n3;;
Says let is unfinished and expects an expression.
Not sure why. mx2 is suppost to get the higher value of the set and move it over to the next function that is in its scope.
I also want to be able to do this such that I dont use any let expressions. Please any help in understanding this language would be really kind
EDIT: Can anyone answer my question below? Also is such a problem possible with out using any let expressions in F#?
Upvotes: 3
Views: 116
Reputation: 762
Says let is unfinished and expects an expression. Not sure why. mx2 is suppost to get the higher value of the set and move it over to the next function that is in its scope.
Regarding this specific question. Every function must return some value. The last "expression" in the function is considered a return value of that function.
let foo a b c =
let x = a + b
y + c
Here, y + c
is the last expression, and it's value is the "return value" of function foo
.
However, declaring and binding some value (let x = a + b
) is a statement, not an expression, and it doesn't have any value, so the following code won't compile.
let foo a b c =
let result = a + b + c
If you wanted to return the value of mx2
in your original code, you'd have to convert the binding statement (let mx2 = ...
) into an expression:
let max3 (n1, n2, n3) =
let mx1 = ...
if (mx1 > n3)
then mx1
else n3
Upvotes: 3
Reputation: 1159
let max3 (n1, n2, n3) = max n1 (max n2 n3)
// val max3 : n1:'a * n2:'a * n3:'a -> 'a when 'a : comparison
max3 (13,4,7)
The max is predefined for 2 parameters and can be composed as above. If you declare no types it will be generic with a constraint that the type 'a needs to have a comparison function.
In F# the function parameters are normally not tuples like (n1, n2, n3), instead it can be defined as
let max3 n1 n2 n3 = max n1 (max n2 n3)
// val max3 : n1:'a -> n2:'a -> n3:'a -> 'a when 'a : comparison
max3 13 4 7
Upvotes: 5