Search code examples
f#unit-type

F#: warning FS0020: This expression should have type 'unit', but has type 'bool'


I'm trying to learn F# by going through some of the Euler problems and I found an issue I haven't been able to figure out. This is my naive solution.

let compute =
    let mutable f = false
    let mutable nr = 0
    while f = false do
        nr <- nr + 20
        f = checkMod nr
    nr

When i do this I get the error message warning FS0020: This expression should have type 'unit', but has type 'bool' on the expression "nr <- nr +20". I've tried rewriting and moving the expressions around and I always get that error on the line below the while statement.

I'm writing this using VS2010 Beta.


Solution

  • The following line:

    f = checkMod nr
    

    is an equality check, not an assignment as I believe you are intending. Change it to:

    f <- checkMod nr
    

    and all should work fine. I'm not sure why you've used the correct syntax on the previous line and not that line...

    Also, the line while f = false do should really be simplified to while not f do; equality checks on booleans are rather convoluted.

    As I side note, I feel a need to point out that you are effectively trying to use F# as an imperative language. Use of mutable variables and while loops are strongly discouraged in functional languages (including F#), especially when a purely functional (and simpler) solution exists, as in this situation. I recommend you read up a bit on programming in the functional style. Of course, just getting to grips with the syntax is a useful thing in itself.