Image Image Image Image Image
Scroll to Top

To Top

pure functional programming

17

Jul
2011

No Comments

In code

By admin

Some examples of pure functional programs that actually do something.

On 17, Jul 2011 | No Comments | In code | By admin

I’ve been struggling with functional programming lately. The part about using pure functions is very easy for me to get, what was/Is difficult is to understand how does a pure program contact with the outside world and manages to keep state.
I then studied a bit about the IO monad, and I managed to understand how to contact with the outside world. The final piece of the puzzle that I’m still missing is out to piece all this together and how to keep the state in a functional way. I’ve coded some very simple examples to teach myself how these things are done. The examples are scala code and use the scalaz library.

In this first example I just read one line at a time from the prompt and then write it back. The app will do this forever until it is killed. The part that causes it looping forever is done by the recursive function forever, which just repeats the same action over and over:

 def forever(theIO:IO[Unit]):IO[Unit] = theIO >>=| forever(theIO)

I find it quite magical way the way this compact syntax encapsulates the action of just doing something over and over again.

import scalaz._
import Scalaz._
import effects._

/*

This program just echo the input

 */

object Test1 {

  def forever(theIO:IO[Unit]):IO[Unit] = theIO >>=| forever(theIO)

  def functionalMain = {
   forever(for(
      line

On the second example I read one line from the prompt and then add it to a list. I was looking for ways to do this without storing this list anywhere. The method that causes the looping in this case is slightly more complicated, because it has to keep propagating an argument forever, by just passing it to the next action. This way we manage to keep state, a list with all the previous strings, without actually storing this list anywhere. Again, I find this quite magical.

import scalaz._
import Scalaz._
import effects._

object Test2 {

  def getStringAndAddToList(list:List[String]):IO[List[String]] =
    for(
      line (A=>IO[A])):A=>IO[A] = makeIO(_) >>= forever(makeIO)

  def functionalMain = {
    val action = forever(getStringAndAddToList _)
    action(Nil)
  }

  def main(args: Array[String]) {
    functionalMain.unsafePerformIO
  }

}

Tags | , ,