Created
December 13, 2018 03:18
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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