F # user linked list and links

I am new to this language. To try to understand the reference, I tried to implement a simple directional list in order to learn a freshman in the learning process.

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? 

Please tell me why I'm bad at this

0
source share
1 answer

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 } // this is how you can change the list let rec append xl = 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 

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

+5
source

Source: https://habr.com/ru/post/1244543/


All Articles