-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathBindful.hs
61 lines (53 loc) · 1.76 KB
/
Bindful.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
-- This file is part of tersmu
-- Copyright (C) 2014 Martin Bays <[email protected]>
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of version 3 of the GNU General Public License as
-- published by the Free Software Foundation.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see http://www.gnu.org/licenses/.
{-# LANGUAGE MultiParamTypeClasses,FunctionalDependencies,TypeSynonymInstances,FlexibleInstances#-}
module Bindful where
-- monad to conveniently handle binding values to numbered variables
import Data.Maybe
import Data.Map (Map)
import qualified Data.Map as Map
import Control.Monad.State
class Monad m => BindfulMonad s m | m -> s where
withBinding :: s -> (Int -> m r) -> m r
binding :: Int -> m s
twiddleBound :: (s -> s) -> m ()
getValues :: m [s]
evalBindful :: m a -> a
-- intended to be private:
nextFree :: m Int
bind :: Int -> s -> m ()
unbind :: Int -> m ()
bindNext :: s -> m ()
type Bindful s = State (Map Int s)
instance BindfulMonad s (Bindful s) where
withBinding v f = do n <- nextFree
bind n v
r <- f n
unbind n
return r
binding n = do bs <- get
case Map.lookup n bs of
Nothing -> error $ "unbound " ++ show n
Just v -> return v
getValues = gets Map.elems
twiddleBound f = do ks <- gets Map.keys
sequence_ $ [ do s <- binding n
bind n (f s)
| n <- ks ]
evalBindful m = evalState m Map.empty
nextFree = do bs <- get
return $ head [ n |
n <- [1..], isNothing $ Map.lookup n bs ]
bind n v = do bs <- get
put $ Map.insert n v bs
unbind n = do bs <- get
put $ Map.delete n bs
bindNext v = do n <- nextFree
bind n v