Created
August 10, 2012 11:19
-
-
Save robcd/3313553 to your computer and use it in GitHub Desktop.
Get vs State
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
// In the following code, Get is a type which has previously been called State - a name which | |
// the author found to be confusing, since instances aren't actually states! | |
// | |
// Instances are in fact functions which obtain (get) a value that depends on some state. | |
// | |
// The following code demonstrates using a Get to set as well as get! | |
// | |
// claim: even this is less confusing than using the name State! | |
// | |
// N.B. Here, 'State' is the type of the er, state. | |
object app extends App { | |
type Get[A, S] = S => (A, S) | |
case class State(n: Int) | |
def set(n: Int): State = { | |
val get = new Get[Unit, State] { | |
def apply(s0: State) = ((), s0) | |
} | |
val (_, s) = get(State(n)) | |
s | |
} | |
def get(s0: State): (Int, State) = { | |
val get = new Get[Int, State] { | |
def apply(s: State) = (s.n, s) | |
} | |
get(s0) | |
} | |
// test that get returns the value passed to set | |
val s0 = set(1) | |
val (n, s1) = get(s0) | |
assert(n == 1) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment