如何使用F#中的函数找到链表的大小(元素数量)?
我想找出链表的大小,如下所示:
type rNumber = Integer of int;;
type lists = Nil | Link of (rNumber * (lists ref));;
let list1 = Link(3, ref (Link(2), ref Nil);
let list2 = Link(6, ref (Link(4), ref Nil);
let list3 = Link(9, ref (Link(6), ref Nil);发布于 2013-04-29 09:59:19
问题是模式匹配只知道标准.Net列表。如果您的Link只是一个元组,那么这将是可行的
let rec length a =
match a with
|Link(_,ref Nil) 0 -> 1
|Link(_,t) -> 1+(length t)编辑:
现在我们知道了Link是如何工作的,这应该能起到作用
let rec length a =
match a with
|Nil -> 0
|Link(_,t) -> 1+(length (!t))!是必需的,因为您在定义中使用了功能不是特别强大的lists ref。
https://stackoverflow.com/questions/16270102
复制相似问题