Reputation: 11659
Here I have a function. In line List.append [0] free_list
it is complaining that, This expression was expected to have type unit but here has a type 'a list
, and it is not clear for me how does it infer that this statment must have an unit type.
let free_list=[]
let find_free_spaces :List<int>=
if 1=1 // The condition is not important
then List.append [0] free_list
free_list
Upvotes: 1
Views: 1931
Reputation: 12184
The compiler is telling you that List.append [0] free_list
returns a value of type int list
but it expects your if then
expression to be of unit
type because you have no else
condition. If you added an else
condition which also returned an int list
, the compiler error would become a warning that you were ignoring the results of an expression.
F# is an expression rather than statement based language, that means if then else...
etc return values (and consequently that those returned values must be of the same type in each case).
Also remember that F# lists are immutable so appending a list does not produce the side effect of adding values to an existing list, it creates a new list containing the original values and the appended values.
As it stands, your code would take a list, build a new list that contains 0 and the list you provided it, do nothing with that new list and finally return the original list you supplied it with. If you did really want that behaviour (for some reason) you could pipe the result of List.append [0] free_list
to the ignore
function which would then make explicit the fact that you are ignoring the result of the if then
expression.
Upvotes: 4
Reputation: 55185
In F#, if/then
and if/then/else
are expressions, not statements (if you're coming from C#, if x then y else z
is like x ? y : z
). If there's an else
clause, then the type of that branch must match the type of the if
branch so that the whole expression is well-typed. If there is no else
, then the if
's body must have type unit
, since otherwise the result would just be disregarded (basically, if x then y
is equivalent to if x then y else ()
).
Upvotes: 2