Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I manage an exclusive state in F#?
    primarykey
    data
    text
    <p>I am not sure about "exclusive state management" thing in the title, I did my best making it up trying to put the problem concisely.</p> <p>I am porting some of my C# code to F# trying to do it as idiomatic as I can. I have an entity that requests a number of ID's from a sequence in my database and then dispenses these ID to anyone in need. Once an id is given out it should no longer be available for anybody else. Hence there must be some sort of state associated with that entity that keeps track of the remaining number of IDs. Since using a mutable state is not idiomatic, what I can do is to write something like this:</p> <pre><code>let createIdManager = let idToStartWith = 127 let allowed = 10 let givenOut = 0 (idToStartWith, allowed, givenOut) - let getNextAvailableId (idToStartWith, allowed, givenOut) = if givenOut&lt; allowed then ((idToStartWith, allowed, givenOut+ 1), Some(idToStartWith + givenOut)) else ((idToStartWith, allowed, givenOut), None) let (idManager, idOpt) = getNextAvailableId createIdManager() match idOpt with | Some(id) -&gt; printf "Yay!" | None -&gt; reloadIdManager idManager |&gt; getNextAvailableId </code></pre> <p>This approach is idiomatic (as far as I can tell) but extremely vulnerable. There are so many ways to get it messed up. My biggest concern is that once an id is advanced and a newer copy of id manager is made, there is no force that can stop you from using the older copy and get the same id again.</p> <p>So how do I do exclusive state management, per se, in F#?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload