What's wrong with this F # code

let compareDiagonal p x y =
    System.Math.Abs((int)(x - (fst p))) <> System.Math.Abs((int)(y  - (snd p)));;

let isAllowed p = function
    | [] -> true
    | list -> List.forall (fun (x, y) -> fst p <> x && snd p <> y && (compareDiagonal p x y))  list;;

let rec solve col list =
    let solCount : int = 0
    match col with
    | col when col < 8 ->
        for row in [0 .. 7] do
            solCount = solCount + if isAllowed (row, col) list then solve (col + 1) ((row, col) :: list) else 0
        solCount        
    | _ -> 1;;

let solCount = solve 0 [];;
solCount;;

I get an error

 solCount = solCount + if isAllowed (row, col) list then (solve (col + 1) ((row, col) :: list)) else 0
------------^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

stdin(335,13): warning FS0020: This expression should have type 'unit', but has type 'bool'. If assigning to a property use the syntax 'obj.Prop <- expr'.

Why can't I return the number?

+4
source share
1 answer

There are two related problems.

By default, the F # variable is immutable. If you want to change a variable, you must declare it as follows:

let mutable solCount : int = 0

And then when you assign values ​​to it instead of using it =, you should use it <-like this:

solCount <- solCount + if isAllowed (row, col) list then solve (col + 1) ((row, col) :: list) else 0

Full example.

, - . . F # , , , .

, " ":

let compareDiagonal p x y =
    System.Math.Abs((int)(x - (fst p))) <> System.Math.Abs((int)(y  - (snd p)));;

let isAllowed p = function
    | [] -> true
    | list -> List.forall (fun (x, y) -> fst p <> x && snd p <> y && (compareDiagonal p x y))  list;;

let rec solve col list =
    let mutable solCount : int = 0
    match col with
    | col when col < 8 ->
        for row in [0 .. 7] do
            solCount <- solCount + if isAllowed (row, col) list then solve (col + 1) ((row, col) :: list) else 0
        solCount        
    | _ -> 1;;

let solCount = solve 0 [];;
solCount;;
+4

All Articles