【问题标题】:Type mismatch error in F#F# 中的类型不匹配错误
【发布时间】:2015-03-18 03:23:02
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

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

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-19
      • 2011-04-01
      • 1970-01-01
      • 2013-01-16
      • 1970-01-01
      • 2021-01-19
      • 2014-02-05
      相关资源
      最近更新 更多