f#链接列表实现记录

时间:2016-03-06 20:10:45

标签: f# linked-list

我正在尝试使用记录在f#中实现链接列表。我知道我可以使用内置列表类型,但这是出于学习目的。我的类型是:

type Cell = { data : int; next : RList}
and RList = Cell option ref

我想创建一个简单的插入函数,但我被告知f#期望一个布尔值,但是给出了一个类型为unit的表达式。我想知道这是否意味着我已经错误地格式化了我的if / else语句

let rec insert comp (item: int) (list: RList) =
    let c = {data = item; next = ref None}
    match !list with
     | None -> list = cellToRList c
     | Some {data = d; next = remaining} -> 
        if (comp(item, d)) then
            c.next := !remaining
            remaining := ref c (* compiler indicates error here *)
        else insert comp item remaining

注意:comp是任何比较函数,将(item,d)作为输入并输出true或false ex:

let compare (x, y) = x > y

如果比较输出为true,我的目标只是插入一个data = item的新单元格。在上面的示例中,它可以用于插入排序列表并维护排序。整个函数应该返回类型单位。关于为什么我的翻译器正在寻找布尔值的任何提示都将不胜感激!

注意:我对F#

很新

====

修复了Foggy,Mikhail和Fyodor提供的改进

type Cell = { data : int; next : (Cell option) ref}

let rec insert compare (item: int) (list: (Cell option) ref) : unit =
    let c = {data = item; next = ref None}
    match !list with
    | None -> list := Some c
    | Some {data = d; next = remaining} -> 
        if (compare(d, item)) then
            c.next := !remaining
            remaining := Some c
        else insert compare item remaining

1 个答案:

答案 0 :(得分:4)

您从None匹配中返回一个bool:

| None -> list = cellToRList c

等号是这里的比较运算符。所以编译器推断函数返回bool,而我想你的意图是返回unit

在任何情况下,只要您不理解函数的推断类型,请尝试明确注释它们。在你的情况下,让它

let rec insert comp (item: int) (list: RList) : unit =

你会看到我上面描述的问题。

一旦编译完所有内容,您可能希望删除类型注释。

相关问题