madhajj
madhajj

Reputation: 69

F# - Append an element to the beginning of a list

so I am trying to append an element to the beginning of a mutable list. This is what I am working with:


type Item<'a> =
    { mutable value: 'a
      mutable next: Option<Item<'a>> }

type MList <'a> =
    { mutable first: Option<Item<'a>>
      mutable last: Option<Item<'a>>
      mutable size: Nat }


let appendFront<'a> (v: 'a) (l: MList <'a>): Unit =

How can I add v to the beginning of the list Mlist?

Upvotes: 0

Views: 231

Answers (1)

Scott Hutchinson
Scott Hutchinson

Reputation: 1721

I would never think to write F# code like this, but this is what you asked for. I hope it helps.

type Nat = int // type alias, since I don't know the definition of Nat

type Item<'a> =
    { mutable Value: 'a
      mutable Next: Option<Item<'a>> }

type MList<'a> =
    { mutable First: Option<Item<'a>>
      mutable Last: Option<Item<'a>>
      mutable Size: Nat }


let appendFront<'a> (v: 'a) (l: MList<'a>): Unit =
    let newItem = { Value = v; Next = l.First }
    l.First <- Some newItem
    l.Size <- l.Size + 1

Upvotes: 4

Related Questions