Skip to content

Instantly share code, notes, and snippets.

@asmodehn
Created May 26, 2021 09:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save asmodehn/8f1efae99ebfdaa3da45bc7683cb3c0f to your computer and use it in GitHub Desktop.
Save asmodehn/8f1efae99ebfdaa3da45bc7683cb3c0f to your computer and use it in GitHub Desktop.
https://wiki.haskell.org/State_Monad with Elixir witchcraft
```elixir
defmodule AlgaeTest do
@moduledoc """
From https://wiki.haskell.org/State_Monad
Example use of State monad
Passes a string of dictionary {a,b,c}
Game is to produce a number from the string.
By default the game is off, a C toggles the
game on and off. A 'a' gives +1 and a b gives -1.
Examples:
# Careful: we are passing charlists here to closely match the behaviour
of the Haskell example..
iex> AlgaeTest.playGame('ab') |> Algae.State.evaluate({false, 0})
0
iex> AlgaeTest.playGame('ca') |> Algae.State.evaluate({false, 0})
1
iex> AlgaeTest.playGame('cabca') |> Algae.State.evaluate({false, 0})
0
State = game is on or off & current score
= (Bool, Int)
"""
use Witchcraft
import Algae.State
@spec playGame(list()) :: Algae.State.t()
def playGame([]) do
monad %Algae.State{} do
{_on, score} <- get()
return(score)
end
end
def playGame([x | xs]) do
monad %Algae.State{} do
{on, score} <- get()
case x do
?a when on -> put({on, score + 1})
?b when on -> put({on, score - 1})
?c -> put({not on, score})
_anything -> put({on, score})
end
playGame(xs)
end
end
end
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment