Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 779563
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 14, 20262026-05-14T19:56:46+00:00 2026-05-14T19:56:46+00:00

What’s a good way to implement mutable data structures in F#? The reason I’m

  • 0

What’s a good way to implement mutable data structures in F#? The reason I’m asking is because I want to go back and implement the data structures I learned about in the algorithms class I took this semester (skip lists, splay trees, fusion trees, y-fast tries, van Emde Boas trees, etc.), which was a pure theory course with no coding whatsoever, and I figure I might as well try to learn F# while I’m doing it. I know that I “should” use finger trees to get splay tree functionality in a functional language, and that I should do something with laziness to get skip-list functionality, etc. , but I want to get the basics nailed down before I try playing with purely functional implementations.

There are lots of examples of how to do functional data structures in F#, but there isn’t much on how to do mutable data structures, so I started by fixing up the doubly linked list here into something that allows inserts and deletes anywhere. My plan is to turn this into a skip list, and then use a similar structure (discriminated union of a record) for the tree structures I want to implement. Before I start on something more substantial, is there a better way to do mutable structures like this in F#? Should I just use records and not bother with the discriminated union? Should I use a class instead? Is this question “not even wrong”? Should I be doing the mutable structures in C#, and not dip into F# until I want to compare them to their purely functional counterparts?

And, if a DU of records is what I want, could I have written the code below better or more idiomatically? It seems like there’s a lot of redundancy here, but I’m not sure how to get rid of it.

module DoublyLinkedList =
    type 'a ll  = 
        | None
        | Node of 'a ll_node
    and 'a ll_node = {
        mutable Prev: 'a ll;
        Element : 'a ;
        mutable Next: 'a ll;
    }

    let insert x l = 
        match l with 
        | None -> Node({ Prev=None; Element=x; Next=None })
        | Node(node) ->
            match node.Prev with
                | None -> 
                    let new_node = { Prev=None; Element=x; Next=Node(node)}
                    node.Prev <- Node(new_node)
                    Node(new_node)
                | Node(prev_node) -> 
                    let new_node = { Prev=node.Prev; Element=x; Next=Node(node)}
                    node.Prev <- Node(new_node)
                    prev_node.Next <- Node(new_node)
                    Node(prev_node)

    let rec nth n l =
        match n, l with
        | _,None -> None
        | _,Node(node) when n > 0 -> nth (n-1) node.Next 
        | _,Node(node) when n < 0 -> nth (n+1) node.Prev 
        | _,Node(node) -> Node(node) //hopefully only when n = 0 :-)

    let rec printLinkedList head = 
        match head with
        | None -> ()
        | Node(x) -> 
            let prev = match x.Prev with
                        | None -> "-"
                        | Node(y) -> y.Element.ToString()
            let cur = x.Element.ToString()
            let next = match x.Next with
                        | None -> "-"
                        | Node(y) -> y.Element.ToString()
            printfn "%s, <- %s -> %s" prev cur next
            printLinkedList x.Next
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-14T19:56:47+00:00Added an answer on May 14, 2026 at 7:56 pm

    I think that the using a discriminated union together with a mutable record is a good approach. Discriminated unions are essential for pattern matching. An alternative to using mutable record would be to create a union case with mutable reference cells:

    // Note: using ´ instead of ' to avoid StackOverflow syntax confusion
    type LinkedList<´T> =  
      | None 
      | Node of (LinkedList<´T> ref) * 'T * (LinkedList<´T> ref)
    

    This may lead to slightly simpler code. For example the insert function would look like this (I didn’t try it, but I think it should be correct):

    let insert x l =  
      match l with  
      | None -> Node(ref None, x, ref None)
      | Node(prev, v, next) as node -> 
          match !prev with 
          | None ->  
             prev := Node(ref None, x, ref node) 
             !prev
          | Node(_, _, prevNextRef) ->  
             prevNextRef := Node(ref (!node.Prev), x, ref node)
             prev := !prevNextRef
             !prevNextRef
    

    However, I don’t think this makes the code much more succinct (maybe even slightly less readable). In any case, you could define active pattern to distinguish among the three cases in the insert function using a single match expression. The following is for your original data structure. This is simply an extractor of the elements stored in a record:

    let (|NodeInfo|) node = (node.Prev, node.Element, node.Next)
    

    For more info, see Active Patterns at MSDN. Then, the insert function would look like this:

    let insert x l =  
        match l with  
        | None -> Node({ Prev=None; Element=x; Next=None }) 
        | Node(NodeInfo(None, _, _) as node) ->
            let new_node = { Prev=None; Element=x; Next=Node(node)} 
            node.Prev <- Node(new_node) 
            Node(new_node) 
        | Node(NodeInfo(Node(prev_node), _, _) as node) ->            
            let new_node = { Prev=node.Prev; Element=x; Next=Node(node)} 
            node.Prev <- Node(new_node) 
            prev_node.Next <- Node(new_node) 
            Node(prev_node) 
    

    [EDIT] Actually, the same thing could be done using patterns for extracting elements of a record, but I think that active patterns may make the code slightly nicer.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 393k
  • Answers 393k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer instead of comparing all the values to each other try… May 15, 2026 at 2:06 am
  • Editorial Team
    Editorial Team added an answer As suggested above would it not make sense (assuming you… May 15, 2026 at 2:06 am
  • Editorial Team
    Editorial Team added an answer Whenever a property on a dynamic object is resolved, the… May 15, 2026 at 2:06 am

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.