繁体   English   中英

F#中的类型不匹配错误

[英]Type mismatch error in F#

下面的脚本应该计算数字的第一个素数因子。 然而,它在第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

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

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)不是该组中的最后一个语句,所以它不应该返回任何内容。

改变第二个ifelif使它工作:

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM