Skip to content

Instantly share code, notes, and snippets.

@gregberns
Created December 13, 2018 03:18
Show Gist options
  • Save gregberns/2cbaa47a5ffbaa9826aa213709200ad8 to your computer and use it in GitHub Desktop.
Save gregberns/2cbaa47a5ffbaa9826aa213709200ad8 to your computer and use it in GitHub Desktop.
An example of the ST Monad to append items to a mutable array
import Data.Array
import Data.Array.ST (empty, push, freeze)
import Data.Either (Either(..))
import Control.Monad.ST.Internal (ST, foreach)
-- Return Rights from an Array of Either's using the ST monad
rights :: forall a b. Array (Either a b) -> Array b
rights array =
let
-- This seems to be required because
inner :: forall c. ST c (Array b)
inner = do
-- Create a new empty array
-- empty :: forall a. f a
arr <- empty
let
insertIfValid e =
case e of
-- push :: forall h a. a -> STArray h a -> ST h Int
Right v -> push v arr *> pure unit
_ -> pure unit
-- foreach :: forall r a. Array a -> (a -> ST r Unit) -> ST r Unit
-- ST.foreach xs f runs the computation returned by the function f for each of the inputs xs.
_ <- foreach array insertIfValid
freeze arr
in
run inner
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment