What would be an elegant way to implement the functionality of this nested class in F#?
private class Aliaser {
private int _count;
internal Aliaser() { }
internal string GetNextAlias() {
return "t" + (_count++).ToString();
}
}
This was my first attempt, but it feels like there should be a sexy one-liner for this:
let aliases = (Seq.initInfinite (sprintf "t%d")).GetEnumerator()
let getNextAlias() =
aliases.MoveNext() |> ignore
aliases.Current
The usual way of writing is to create a function with local state captured in a closure:
The type of
getNextAliasis simplyunit -> stringand when you call it repeatedly, it returns strings “t1”, “t2”, … This relies on mutable state, but the mutable state is hidden from the user.Regarding whether you can do this without mutable state – the simple answer is NO, because when you call a purely functional function with the same parameter twice, it must return the same result. Thus, you’d have to write something with the following structure:
As you can see, you’d need to keep some state and maintain it through the whole code. In F#, the standard way of dealing with this is to use mutable state. In Haskell, you could use State monad, which allows you to hide the passing of the state. Using the implementation from this question, you could write something like:
This is quite similar to other computations such as
lazyorseq, actually – computations in thestate { .. }block have some state and you can execute them by providing initial value of the state. However, unless you have good reasons for requiring purely functional solution, I’d prefer the first version for practical F# programming.