-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreader.go
More file actions
74 lines (61 loc) · 1.75 KB
/
reader.go
File metadata and controls
74 lines (61 loc) · 1.75 KB
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
62
63
64
65
66
67
68
69
70
71
72
73
74
package reader
// EnvKey is some identifier, used to extract a value out of the environment
type EnvKey string
// EnvVal represents the value at a given key
type EnvVal interface{}
// Env is the Env that our Reader works with
type Env map[EnvKey]EnvVal
// MonadReader is a reader, with access to it's environment
type MonadReader struct {
Reader
Env Env
}
// Ask returns the current environment from the reader
func (m MonadReader) Ask() Env {
return m.Env
}
// Bind is defined as MonadReader r a -> (r -> MonadReader r a) -> MonadReader r a
// Bind takes in a function which accepts an env,
// and returns a new MonadReader
func (m MonadReader) Bind(fn func(env Env) MonadReader) MonadReader {
return fn(m.Ask())
}
// With takes a function that takes an env,
// and the MonadReader supplies the env the function
func (m MonadReader) With(fn func(env Env)) {
fn(m.Ask())
}
// Reader is a function which given an environment, will return some value
type Reader interface {
Run(Env) EnvVal
}
// AReader is type representing an instance of a the interface Reader
type AReader func(Env) EnvVal
// Run allows AReader to satisfy the Reader interface
// When you some reader says r.Run(someEnv) it is the same as saying r(someEnv)
func (runReader AReader) Run(env Env) EnvVal {
return runReader(env)
}
// KVReader will return a MonadReader,
// and set the env[k] = v
func KVReader(env Env, k EnvKey, v EnvVal) MonadReader {
env[k] = v
return MonadReader{
AReader(func(env Env) EnvVal {
return env[k]
}),
env,
}
}
// NewReader takes in an environment and gives you an empty Reader
func NewReader(env Env) MonadReader {
return MonadReader{
AReader(func(env Env) EnvVal {
return ""
}),
env,
}
}
func NewEnv() map[EnvKey]EnvVal {
return map[EnvKey]EnvVal{}
}