1
votes

Based on the question How can I re-assign a variable in a function in Haskell?, there is a haskell solution to change the total congo elephant count Congo 0 in a function:

main' :: StateT Congo IO ()
main' =
  do
    printElephant
    function 2
    printElephant

-- run program:
main :: IO ()
main = Congo 0 & runStateT main' & void
-- outputs:
0
2

After reading the Computation Expression series, I still don't know how to write a CE builder for this problem correctly. How can I re-assign a variable in a function with F#'s CE?

1
You're going to have to explain what you're trying to do in much more detail. A fragment of Haskell code (missing critical pieces) doesn't seem to explain what you're trying to accomplish in F#. - dfeuer
F# isn't pure like Haskell and has mutable variables built-in. Or are you asking how to implement the state monad in F#? - Lee
@MiP - Since you've read the Computation Expression series and you're wanting to figure out how to implement the State monad, the next series you read should almost certainly be fsharpforfunandprofit.com/series/handling-state.html, in which Scott Wlaschin explains that particular pattern with humor, his usual excellent diagrams, and a very fun metaphor. - rmunn
@dfeuer you could see the code at the first link. Haskell seems so different comparing to F# so I don't fully know how to translate this code into F#. - MiP
What have you tried so far? Where are you stuck? - Mark Seemann

1 Answers

3
votes

F# has a first-class support for imperative programming constructs. You just need to mark your let bindings as mutable. There is no need for computation expressions in this case:

let mutable elephant = 0
printfn "Elephant = %d" elephant
elephant <- 2
printfn "Elephant = %d" elephant