1

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?

leftaroundabout
  • 117,950
  • 5
  • 174
  • 319
MiP
  • 5,846
  • 3
  • 26
  • 41
  • 2
    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 Jun 07 '17 at 15:37
  • 5
    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 Jun 07 '17 at 15:38
  • @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 https://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 Jun 07 '17 at 16:12
  • @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 Jun 07 '17 at 16:39
  • 3
    What have you tried so far? Where are you stuck? – Mark Seemann Jun 07 '17 at 17:50

1 Answers1

3

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
Tomas Petricek
  • 240,744
  • 19
  • 378
  • 553
  • Although `mutable` can handle most of the use cases, my question is asking how to implement state monad in F# though. – MiP Jun 12 '17 at 12:56