Edelweiss
Edelweiss

Reputation: 79

Does F# have object reference or does it copy the object

Let's say I want to implement a doubly linked list in F# as a class. So far I have started with the following code:

type List<'T>(?value : 'T, ?head : List<'T>, ?tail : List<'T>) =

    let mutable v : 'T = defaultArg value Unchecked.defaultof<'T>
    let mutable h : List<'T> option = head
    let mutable t : List<'T> option = tail

    member this.value with get() = v and set(value) = v <- value
    member this.head with get() = h and set(head) = h <- head
    member this.tail with get() = t and set(tail) = t <- tail

Here, I have 3 questions mainly.

  1. Is this a good way to implement the doubly linked list in F#?
  2. What happens when setting the head to some list, does the whole object get copied or do I have only a reference to it? In the best case, I would only want a reference to the object.
  3. What happens if I use the ref keyword in F#? It's called a reference, but does it work like a pointer in C/C++?

Upvotes: 1

Views: 195

Answers (1)

tranquillity
tranquillity

Reputation: 1685

Seems like you are new to F# and coming from an OO background where mutable is the natural and default way to do things. I'm not sure what the best way to implement a doubly linked list is in F# but probably the best way to learn about how collections should be implemented in a natural way for a particular language is to look at what existing libraries are doing. Check out FSharpx.Collections for more advanced collections like doubly linked lists or the F# core library for the standard ones.

Upvotes: 2

Related Questions