First of all, you are trying to implement it in some imperative way - this is normal, but not very functional. Anyway, the first thing you come across is that you cannot assign null
- if you really want to add [<AllowNullLiteral>]
to the item
type (but, of course, you need to make it a class instead of an entry):
[<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
But this is almost never a good idea, so I would start like this:
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 }
Now, if you look carefully, you will see that you really do not need links, if you just added to the front and voila ... you have your usual functional list;)
PS: you also forgot something:
- you use floats there, so you need to use
0.0
instead of 0
- your
sum
function must be recursive (remember that you are not tail-recursive, so you will have problems with large lists!) - you need to dereference
ref
-cells with !
- you need to build
ref
-cells with ref
(e.g. ref null
) - your
type list() =
didn't make any sense to me, so I converted it to a module
PPS: please, not that it is not F # -Way to mutate things like this - just show you how you can do it ... but don't do this if you don't need
source share