簡體   English   中英

F#類型“ int列表”與類型“ int”不匹配

[英]F# Type 'int list' does not match the type 'int'

我正在嘗試構建一個包含斐波那契數列的列表,但是當我稍后嘗試調用該函數時,它告訴我int列表與int不匹配,

let rec fibonacci x list =
    if List.head list > x then List.tail list
    else fibonacci x (List.append (List.head list + (List.head (List.tail list))) list)


let x = 10
let list = [1;2]
let fibonacciList = fibonacci x list
printf "%A" fibonacciList

它說編輯器在最后第二行的函數調用中。
我是F#的新手,我敢肯定這是一個基本的定義錯誤,但我無法弄清楚它是什么

當您刪除對fibonacci函數的調用時,編譯器實際上會顯示出真正的錯誤: error FS0071: Type constraint mismatch when applying the default type ''a list' for a type inference variable. The types ''a' and ''a list' cannot be unified. Consider adding further type constraints error FS0071: Type constraint mismatch when applying the default type ''a list' for a type inference variable. The types ''a' and ''a list' cannot be unified. Consider adding further type constraints

這很難理解,但基本上實現有問題。 我認為問題是您對List.append的使用。 它應該有兩個列表,但您需要為其提供一個int和一個int list 您可以使用::運算符將一項添加到列表的::

let rec fibonacci x list =
    if List.head list > x then List.tail list
    else fibonacci x ((List.head list + (List.head (List.tail list))) :: list)

這是使用模式匹配來簡化代碼的等效實現:

let rec fibonacci x list =
    match list with
    | a :: b :: rest ->
        if a > x then b :: rest
        else fibonacci x (a + b :: list)

請注意,編譯器警告匹配項不完整。 如果列表中的項目少於2個,則此函數將引發異常。

還要注意,這不能正常工作:它不會產生斐波那契數列。 我將把它留給您解決。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM