use*_*085 0 recursion f# list ref
我是这门语言的新手.为了尝试和理解参考我已经尝试实施一个简单的定向列表新生大学计算机科学的方式.
type item = {
value:float
next:ref<item>
}
type list() =
let head:ref<item> = null // tried instantiation so many different ways and it likes none of em
let sum i =
if i == null then
0
else
i.value + sum i.next // constructor not defined?
Run Code Online (Sandbox Code Playgroud)
请告诉我为什么我不好
首先,您尝试以某种必要的方式实现它 - 这没关系,但不是真正的功能.无论如何,你遇到问题的第一件事是你不能分配null
- 如果你真的想要添加[<AllowNullLiteral>]
你的item
类型(当然你必须把它变成一个类而不是一个记录):
[<AllowNullLiteral>]
type Item(value, next) =
member this.value = value
member this.next : Item ref = next
let head : ref<Item> = ref null
let rec sum (i : Item) =
if i = null then
0.0
else
i.value + sum !i.next
Run Code Online (Sandbox Code Playgroud)
但这几乎不是一个好主意,所以我会这样开始:
module List =
type Item = { value : float; next : List }
and List = Item option ref
let empty : List = ref None
let single x = { value = x; next = ref None }
// this is how you can change the list
let rec append x l =
let item = singleton x
match !l with
| None ->
l := Some item
| Some node ->
append x node.next
let rec sum (l : List) =
match !l with
| None -> 0.0
| Some item -> item.value + sum item.next
Run Code Online (Sandbox Code Playgroud)
现在,如果你仔细观察,如果你只是附加在前面,那么你会发现你并不真正需要参考...你得到了通常的功能列表;)
PS:你也忘记了其他一些事情:
0.0
而不是0
sum
函数必须是递归的(请注意,它不是尾递归的,所以你会遇到大列表的问题!)ref
-cells!
ref
-cells ref
(例如ref null
)type list() =
对我毫无意义所以我把它转换成了一个模块PPS:请注意,这不是F# -要改变这样的事情 - 它只是告诉你如何做到这一点......但如果你不需要,那就不要