F#中的类型不匹配错误

时间:2015-01-20 01:07:27

标签: function f# functional-programming f#-interactive f#-3.0

下面的脚本应计算数字的第一个素数因子。但是,它在第​​10行抛出错误,char 28

 ~vs7F27.fsx(10,28): error FS0001: Type mismatch. Expecting a
 unit list    
 but given a
 int64 list    
 The type 'unit' does not match the type 'int64'

我的代码如下。为什么它需要一个单位作为这里的类型?如何更改我的代码以允许int64?

let makeList x  = [2L..(x-1L)]
let divides x y = x%y = 0L
let isprime n =
    let rec check i =
        i > n/2L || (n % i <> 0L && check (i + 1L))
    check 2L
let findFirstPrimeFactor x = 
    let rec find y list = 
        if divides y (list |> List.head) &&  list |> List.head |> isprime 
            then List.head(list)
        if list |> List.length <> 1 then 1L
        else find y (list |> List.tail)
    find x (makeList x)

findFirstPrimeFactor 7L

1 个答案:

答案 0 :(得分:3)

您的代码缩进具有误导性。它应该更像是

let findFirstPrimeFactor x = 
    let rec find y list = 
        if divides y (list |> List.head) &&  list |> List.head |> isprime 
            then List.head(list)
                 if list |> List.length <> 1 then 1L
        else find y (list |> List.tail)
    find x (makeList x)

这就是您收到错误的原因 - List.head(list)不是该组中的最后一条语句,因此它不应返回任何内容。

将第二个if更改为elif以使其有效:

let findFirstPrimeFactor x = 
    let rec find y list = 
        if divides y (list |> List.head) &&  list |> List.head |> isprime 
            then List.head(list)
        elif list |> List.length <> 1 then 1L
        else find y (list |> List.tail)
    find x (makeList x)