4
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;;

エラーが発生しています

 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'.

番号を返せないのはなぜですか?

4

1 に答える 1

4

2 つの関連する問題があります。

デフォルトでは、F# 変数は不変です。変更可能な変数が必要な場合は、次のように宣言する必要があります。

let mutable solCount : int = 0

そして、使用する代わりにそれに値を代入するときは、次のよう=に使用する必要があります<-:

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

完全な例が続きました。

ただし、これはこのようなことを行うための正しい機能的な方法ではありません。ループを使用して値を加算する代わりに、再帰関数を使用して累積値を返します。関数型プログラムが使用されるように設計された方法で 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;;
于 2013-10-13T04:20:42.843 に答える