下面的脚本应计算数字的第一个素数。但是,它在第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)
不是该组中的最后一个语句,因此它不应返回任何内容。
更改秒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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句