alvinalexander.com | career | drupal | java | mac | mysql | perl | scala | uml | unix  

Scala example source code file (State.scala)

This example Scala source code file (State.scala) is included in the alvinalexander.com "Java Source Code Warehouse" project. The intent of this project is to help you "Learn Scala by Example" TM.

Learn more about this Scala project at its project page.

Java - Scala tags/keywords

indexedstate, indexedstatefunctions, state, unit

The State.scala Scala example source code

package scalaz


trait IndexedStateFunctions {
  def constantIndexedState[S1, S2, A](a: A, s: => S2): IndexedState[S1, S2, A] =
    IndexedState((_: S1) => (s, a))

  def iPut[S1, S2](s: S2): IndexedState[S1, S2, Unit] = IndexedState(_ => (s, ()))

  def iModify[S1, S2](f: S1 => S2): IndexedState[S1, S2, Unit] = IndexedState(s => {
    val r = f(s);
    (r, ())
  })
}

trait StateFunctions extends IndexedStateFunctions {
  def constantState[S, A](a: A, s: => S): State[S, A] =
    State((_: S) => (s, a))

  def state[S, A](a: A): State[S, A] =
    State((_ : S, a))

  def init[S]: State[S, S] = State(s => (s, s))

  def get[S]: State[S, S] = init

  def gets[S, T](f: S => T): State[S, T] = State(s => (s, f(s)))

  def put[S](s: S): State[S, Unit] = State(_ => (s, ()))

  def modify[S](f: S => S): State[S, Unit] = State(s => {
    val r = f(s);
    (r, ())
  })
}

Other Scala examples (source code examples)

Here is a short list of links related to this Scala State.scala source code file:

... this post is sponsored by my books ...

#1 New Release!

FP Best Seller

 

new blog posts

 

Copyright 1998-2024 Alvin Alexander, alvinalexander.com
All Rights Reserved.

A percentage of advertising revenue from
pages under the /java/jwarehouse URI on this website is
paid back to open source projects.