Skip to content

Instantly share code, notes, and snippets.

@ssimeonov
Created January 19, 2016 17:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ssimeonov/e61c40808d3cd13016c1 to your computer and use it in GitHub Desktop.
Save ssimeonov/e61c40808d3cd13016c1 to your computer and use it in GitHub Desktop.
Code for Travis Brown's answer to State Transformations with a Shapless State Monad (http://stackoverflow.com/questions/34870889/state-transformations-with-a-shapeless-state-monad)
package ss
object ContrivedAdd {
import shapeless._
import record._
import syntax.singleton._
import scalaz._
import Scalaz._
def transform[S, T](f: S => T): IndexedState[S, T, Unit] =
IndexedState(s => (f(s), ()))
def addField[K <: Symbol, A, L <: HList](k: Witness.Aux[K], a: A)(
f: Int => Int
): IndexedState[S[L], S[FieldType[K, A] :: L], Unit] =
IndexedState(s => (S(f(s.total), field[K](a) :: s.scratch), ()))
case class S[L <: HList](total: Int, scratch: L)
def contrivedAdd[L <: HList](n: Int) = for {
a <- init[S[L]]
_ <- addField('latestAdded, n)(_ + n)
r <- get
} yield r.total
def main(args: Array[String] = Array()): Unit = {
val initialState = S(0, ('someDefault ->> 1) :: HNil)
val result = contrivedAdd(555).run(initialState)
println(result)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment