This page is no longer maintained — Please continue to the home page at www.scala-lang.org

MVC in functional programming

35 replies
Samuel Robert Reid
Joined: 2008-12-17,
User offline. Last seen 1 year 22 weeks ago.

Scala Community,

I have a problem that I would normally solve using the
model-view-controller paradigm with imperative/procedural code, and was
wondering how this type of problem could be addressed with functional
programming, particularly with respect to immutable objects. What does
a functional programmer do for mvc type problems?

Thanks,
Sam Reid

David Pollak
Joined: 2008-12-16,
User offline. Last seen 42 years 45 weeks ago.
Re: MVC in functional programming
Sam,
Scala does very well in the MVC paradigm (I'm talk real Smalltalk style MVC, not the pseudo web MVC that Rails and Struts purport to have).
Passing immutable data structures makes multithreaded coding a lot simpler.  You know the events that your MVC code receives won't be mutated out from under you.
Scala's Actors provide a very nice way to do MVC.  But you can be a little more type-safe and use functions or partial functions as parameters for your listeners.
Thanks,
David  

On Sat, Jan 3, 2009 at 7:43 PM, Samuel Robert Reid <Reids [at] colorado [dot] edu> wrote:
Scala Community,

I have a problem that I would normally solve using the model-view-controller paradigm with imperative/procedural code, and was wondering how this type of problem could be addressed with functional programming, particularly with respect to immutable objects.  What does a functional programmer do for mvc type problems?

Thanks,
Sam Reid



--
Lift, the simply functional web framework http://liftweb.net
Collaborative Task Management http://much4.us
Follow me: http://twitter.com/dpp
Git some: http://github.com/dpp
Warren Henning
Joined: 2008-12-31,
User offline. Last seen 42 years 45 weeks ago.
Re: MVC in functional programming

On Sun, Jan 4, 2009 at 1:04 AM, David Pollak
wrote:
> Scala does very well in the MVC paradigm (I'm talk real Smalltalk style MVC,
> not the pseudo web MVC that Rails and Struts purport to have).

Are there any projects that implement the MVC pattern in a reasonably
self-contained/didactic way which people can look at now without
having to code something from scratch?

Warren

David Pollak
Joined: 2008-12-16,
User offline. Last seen 42 years 45 weeks ago.
Re: MVC in functional programming


On Sun, Jan 4, 2009 at 2:10 AM, Warren Henning <warren [dot] henning [at] gmail [dot] com> wrote:
On Sun, Jan 4, 2009 at 1:04 AM, David Pollak
<feeder [dot] of [dot] the [dot] bears [at] gmail [dot] com> wrote:
> Scala does very well in the MVC paradigm (I'm talk real Smalltalk style MVC,
> not the pseudo web MVC that Rails and Struts purport to have).

Are there any projects that implement the MVC pattern in a reasonably
self-contained/didactic way which people can look at now without
having to code something from scratch?

Not that I know of.  There might be some Scala Swing open source apps floating around. 


Warren



--
Lift, the simply functional web framework http://liftweb.net
Collaborative Task Management http://much4.us
Follow me: http://twitter.com/dpp
Git some: http://github.com/dpp
Sean McDirmid
Joined: 2008-12-17,
User offline. Last seen 42 years 45 weeks ago.
Re: MVC in functional programming
Has there ever been a reusable implementation of the MVC pattern that can be instantiated across multiple problem domains? Nah, this is why MVC is a pattern. There is some support for observable collections in the core library, which could be the basis for an arbitrary MVC system based on collections. 
I've almost completely drifted away from relying on MVC as a strict pattern, its much easier to just mix view and data with constraint-based programming. See naked objects, or maybe FRP (although some people swear FRP is MVC-based, it seems like the exact opposite of MVC). You also have the option in Scala of layered modularization through mixins, which blurs the line even further.
Scala is a powerful language, so you could reasonably follow almost any pattern you wanted (functional or not).    

On Sun, Jan 4, 2009 at 6:10 PM, Warren Henning <warren [dot] henning [at] gmail [dot] com> wrote:
On Sun, Jan 4, 2009 at 1:04 AM, David Pollak
<feeder [dot] of [dot] the [dot] bears [at] gmail [dot] com> wrote:
> Scala does very well in the MVC paradigm (I'm talk real Smalltalk style MVC,
> not the pseudo web MVC that Rails and Struts purport to have).

Are there any projects that implement the MVC pattern in a reasonably
self-contained/didactic way which people can look at now without
having to code something from scratch?

Warren

Fred Janon
Joined: 2009-01-02,
User offline. Last seen 2 years 9 weeks ago.
Re: MVC in functional programming
Check PureMVC, there is no Scala port at the moment but maybe someone will do it soon?

http://puremvc.org/content/view/67/178/


Fred

On Sun, Jan 4, 2009 at 20:34, Sean McDirmid <sean [dot] mcdirmid [at] gmail [dot] com> wrote:
Has there ever been a reusable implementation of the MVC pattern that can be instantiated across multiple problem domains? Nah, this is why MVC is a pattern. There is some support for observable collections in the core library, which could be the basis for an arbitrary MVC system based on collections. 
I've almost completely drifted away from relying on MVC as a strict pattern, its much easier to just mix view and data with constraint-based programming. See naked objects, or maybe FRP (although some people swear FRP is MVC-based, it seems like the exact opposite of MVC). You also have the option in Scala of layered modularization through mixins, which blurs the line even further.
Scala is a powerful language, so you could reasonably follow almost any pattern you wanted (functional or not).    

On Sun, Jan 4, 2009 at 6:10 PM, Warren Henning <warren [dot] henning [at] gmail [dot] com> wrote:
On Sun, Jan 4, 2009 at 1:04 AM, David Pollak
<feeder [dot] of [dot] the [dot] bears [at] gmail [dot] com> wrote:
> Scala does very well in the MVC paradigm (I'm talk real Smalltalk style MVC,
> not the pseudo web MVC that Rails and Struts purport to have).

Are there any projects that implement the MVC pattern in a reasonably
self-contained/didactic way which people can look at now without
having to code something from scratch?

Warren


Samuel Robert Reid
Joined: 2008-12-17,
User offline. Last seen 1 year 22 weeks ago.
Re: MVC in functional programming
I see the advantages of using immutable event objects, actors and first class functions for implementing MVC pattern in Scala, but still am unclear about how a functional program would handle the MVC pattern's prescription to call mutators on the Model, while keeping the Model "as immutable as possible".  To be specific, here is a small piece of code that implements MVC in imperative Java (see below).   How would this same problem be solved in a pure functional language, or only using purely functional aspects of Scala?  Would a new Model be created each time setState is called?  If so, how would the View be notified about this?  What if JFrames and other GUI elements were immutable, would they be recreated with the new correct state each time there is a model change?  Or is this problem too awkward to handle elegantly with functional programming, and  imperative programming + mutable Model (& View JFrame) is better?

Thanks,
Sam Reid

class Model {
        int state;
        ArrayList listeners;
        void setState( int state ) {this.state = state;
            for ( int i = 0; i < listeners.size(); i++ ) {
                ((Listener) listeners.get( i )).modelChanged();
            }
        }
        int getState() {return state;}
        void addListener(Listener listener){listeners.add(listener);}
    }
    interface Listener{
        void modelChanged();
    }
    class Controller {
        Model model;
        Controller( Model model ) {this.model = model;}
        void incrementModel() {model.setState( model.getState()+1);}
    }
    class View{
        Model model;
        JFrame frame;
        View( final Model model ) {
            this.model = model;
            model.addListener(new Listener(){
                public void modelChanged(){
                    frame.setSize( model.getState(),model.getState() );
                }
            });
        }
    }

David Pollak wrote:
cdbebedf0901040104q56213e4aq86b1ba2294879c85 [at] mail [dot] gmail [dot] com" type="cite">Sam,
Scala does very well in the MVC paradigm (I'm talk real Smalltalk style MVC, not the pseudo web MVC that Rails and Struts purport to have).
Passing immutable data structures makes multithreaded coding a lot simpler.  You know the events that your MVC code receives won't be mutated out from under you.
Scala's Actors provide a very nice way to do MVC.  But you can be a little more type-safe and use functions or partial functions as parameters for your listeners.
Thanks,
David  

On Sat, Jan 3, 2009 at 7:43 PM, Samuel Robert Reid <Reids [at] colorado [dot] edu" rel="nofollow">Reids [at] colorado [dot] edu> wrote:
Scala Community,

I have a problem that I would normally solve using the model-view-controller paradigm with imperative/procedural code, and was wondering how this type of problem could be addressed with functional programming, particularly with respect to immutable objects.  What does a functional programmer do for mvc type problems?

Thanks,
Sam Reid



David Pollak
Joined: 2008-12-16,
User offline. Last seen 42 years 45 weeks ago.
Re: MVC in functional programming
class Model extends Actor {
  private state: Int = 0
  private listeners: List[Actor] = Nil
  def act =loop {
    react {
          case AddListener(who) => listeners = who :: listeners
          case RemoveListener(who) => listeners = listeners.remove(who.eq)
          case SetState(st: Int) => state = st; listeners.foreach(_ ! TheState(this, state))
          case GetState => reply(TheState(this, state))
        }
  }
}

case class AddListener(who: Actor)
case class RemoveListener(who: Actor)
case class SetState(st: Int)
case class TheState(model: Actor, state: Int)
case object GetState

class Controller(model: Actor) {
  def incModel = (model !? GetState) match {
    case TheState(_, st) => model ! SetState(st + 1)
  }
}

class View(model: Actor) extends Actor {
  model ! AddListener(this)
  JFrame frame;
 
  def act {
    loop {
      react {
        case TheState(_, st) => frame.setSize(st, st)
      }
    }
  }
}     

On Sun, Jan 4, 2009 at 7:27 AM, Samuel Robert Reid <Reids [at] colorado [dot] edu> wrote:
I see the advantages of using immutable event objects, actors and first class functions for implementing MVC pattern in Scala, but still am unclear about how a functional program would handle the MVC pattern's prescription to call mutators on the Model, while keeping the Model "as immutable as possible".  To be specific, here is a small piece of code that implements MVC in imperative Java (see below).   How would this same problem be solved in a pure functional language, or only using purely functional aspects of Scala?  Would a new Model be created each time setState is called?  If so, how would the View be notified about this?  What if JFrames and other GUI elements were immutable, would they be recreated with the new correct state each time there is a model change?  Or is this problem too awkward to handle elegantly with functional programming, and  imperative programming + mutable Model (& View JFrame) is better?

Thanks,
Sam Reid

class Model {
        int state;
        ArrayList listeners;
        void setState( int state ) {this.state = state;
            for ( int i = 0; i < listeners.size(); i++ ) {
                ((Listener) listeners.get( i )).modelChanged();
            }
        }
        int getState() {return state;}
        void addListener(Listener listener){listeners.add(listener);}
    }
    interface Listener{
        void modelChanged();
    }
    class Controller {
        Model model;
        Controller( Model model ) {this.model = model;}
        void incrementModel() {model.setState( model.getState()+1);}
    }
    class View{
        Model model;
        JFrame frame;
        View( final Model model ) {
            this.model = model;
            model.addListener(new Listener(){
                public void modelChanged(){
                    frame.setSize( model.getState(),model.getState() );
                }
            });
        }
    }

David Pollak wrote:
Sam,
Scala does very well in the MVC paradigm (I'm talk real Smalltalk style MVC, not the pseudo web MVC that Rails and Struts purport to have).
Passing immutable data structures makes multithreaded coding a lot simpler.  You know the events that your MVC code receives won't be mutated out from under you.
Scala's Actors provide a very nice way to do MVC.  But you can be a little more type-safe and use functions or partial functions as parameters for your listeners.
Thanks,
David  

On Sat, Jan 3, 2009 at 7:43 PM, Samuel Robert Reid <Reids [at] colorado [dot] edu> wrote:
Scala Community,

I have a problem that I would normally solve using the model-view-controller paradigm with imperative/procedural code, and was wondering how this type of problem could be addressed with functional programming, particularly with respect to immutable objects.  What does a functional programmer do for mvc type problems?

Thanks,
Sam Reid



Samuel Robert Reid
Joined: 2008-12-17,
User offline. Last seen 1 year 22 weeks ago.
Re: MVC in functional programming
David,

Thanks for your thoughtful response.  Just to be clear, though, the example you provided is not 100% pure functional, because the state and listeners in the Model are var instead of val.  Maybe it makes no sense to do 100% pure functional for MVC pattern, since the model needs to have state changes.

Thanks again,
Sam Reid

David Pollak wrote:
cdbebedf0901041112k2fe10c30p69f42b3be9bbea2e [at] mail [dot] gmail [dot] com" type="cite">class Model extends Actor {
  private state: Int = 0
  private listeners: List[Actor] = Nil
  def act =loop {
    react {
          case AddListener(who) => listeners = who :: listeners
          case RemoveListener(who) => listeners = listeners.remove(who.eq)
          case SetState(st: Int) => state = st; listeners.foreach(_ ! TheState(this, state))
          case GetState => reply(TheState(this, state))
        }
  }
}

case class AddListener(who: Actor)
case class RemoveListener(who: Actor)
case class SetState(st: Int)
case class TheState(model: Actor, state: Int)
case object GetState

class Controller(model: Actor) {
  def incModel = (model !? GetState) match {
    case TheState(_, st) => model ! SetState(st + 1)
  }
}

class View(model: Actor) extends Actor {
  model ! AddListener(this)
  JFrame frame;
 
  def act {
    loop {
      react {
        case TheState(_, st) => frame.setSize(st, st)
      }
    }
  }
}     

On Sun, Jan 4, 2009 at 7:27 AM, Samuel Robert Reid <Reids [at] colorado [dot] edu" rel="nofollow">Reids [at] colorado [dot] edu> wrote:
I see the advantages of using immutable event objects, actors and first class functions for implementing MVC pattern in Scala, but still am unclear about how a functional program would handle the MVC pattern's prescription to call mutators on the Model, while keeping the Model "as immutable as possible".  To be specific, here is a small piece of code that implements MVC in imperative Java (see below).   How would this same problem be solved in a pure functional language, or only using purely functional aspects of Scala?  Would a new Model be created each time setState is called?  If so, how would the View be notified about this?  What if JFrames and other GUI elements were immutable, would they be recreated with the new correct state each time there is a model change?  Or is this problem too awkward to handle elegantly with functional programming, and  imperative programming + mutable Model (& View JFrame) is better?

Thanks,
Sam Reid

class Model {
        int state;
        ArrayList listeners;
        void setState( int state ) {this.state = state;
            for ( int i = 0; i < listeners.size(); i++ ) {
                ((Listener) listeners.get( i )).modelChanged();
            }
        }
        int getState() {return state;}
        void addListener(Listener listener){listeners.add(listener);}
    }
    interface Listener{
        void modelChanged();
    }
    class Controller {
        Model model;
        Controller( Model model ) {this.model = model;}
        void incrementModel() {model.setState( model.getState()+1);}
    }
    class View{
        Model model;
        JFrame frame;
        View( final Model model ) {
            this.model = model;
            model.addListener(new Listener(){
                public void modelChanged(){
                    frame.setSize( model.getState(),model.getState() );
                }
            });
        }
    }

David Pollak wrote:
Sam,
Scala does very well in the MVC paradigm (I'm talk real Smalltalk style MVC, not the pseudo web MVC that Rails and Struts purport to have).
Passing immutable data structures makes multithreaded coding a lot simpler.  You know the events that your MVC code receives won't be mutated out from under you.
Scala's Actors provide a very nice way to do MVC.  But you can be a little more type-safe and use functions or partial functions as parameters for your listeners.
Thanks,
David  

On Sat, Jan 3, 2009 at 7:43 PM, Samuel Robert Reid <Reids [at] colorado [dot] edu" target="_blank" rel="nofollow">Reids [at] colorado [dot] edu> wrote:
Scala Community,

I have a problem that I would normally solve using the model-view-controller paradigm with imperative/procedural code, and was wondering how this type of problem could be addressed with functional programming, particularly with respect to immutable objects.  What does a functional programmer do for mvc type problems?

Thanks,
Sam Reid



Jorge Ortiz
Joined: 2008-12-16,
User offline. Last seen 29 weeks 3 days ago.
Re: MVC in functional programming
It's possible to get rid of vars if you really want to, though I think David's original code is preferable by far:

  def loop(state: Int, listeners: List[Actor], notify: Boolean) = {
    if (notify) listeners.foreach(_ ! TheState(this, state))
    react {
      case AddListener(who) => loop(state, who :: listeners, false)
      case RemoveListener(who) => loop(state, listeners.remove(who.eq), false)
      case SetState(st: Int) => loop(st, listeners, true)
      case GetState => reply(TheState(this, state)); loop(state, listeners, false)
    }
  }

--j

On Sun, Jan 4, 2009 at 1:19 PM, Samuel Robert Reid <Reids [at] colorado [dot] edu> wrote:
David,

Thanks for your thoughtful response.  Just to be clear, though, the example you provided is not 100% pure functional, because the state and listeners in the Model are var instead of val.  Maybe it makes no sense to do 100% pure functional for MVC pattern, since the model needs to have state changes.

Thanks again,
Sam Reid

David Pollak wrote:
class Model extends Actor {
  private state: Int = 0
  private listeners: List[Actor] = Nil
  def act =loop {
    react {
          case AddListener(who) => listeners = who :: listeners
          case RemoveListener(who) => listeners = listeners.remove(who.eq)
          case SetState(st: Int) => state = st; listeners.foreach(_ ! TheState(this, state))
          case GetState => reply(TheState(this, state))
        }
  }
}

case class AddListener(who: Actor)
case class RemoveListener(who: Actor)
case class SetState(st: Int)
case class TheState(model: Actor, state: Int)
case object GetState

class Controller(model: Actor) {
  def incModel = (model !? GetState) match {
    case TheState(_, st) => model ! SetState(st + 1)
  }
}

class View(model: Actor) extends Actor {
  model ! AddListener(this)
  JFrame frame;
 
  def act {
    loop {
      react {
        case TheState(_, st) => frame.setSize(st, st)
      }
    }
  }
}     

On Sun, Jan 4, 2009 at 7:27 AM, Samuel Robert Reid <Reids [at] colorado [dot] edu> wrote:
I see the advantages of using immutable event objects, actors and first class functions for implementing MVC pattern in Scala, but still am unclear about how a functional program would handle the MVC pattern's prescription to call mutators on the Model, while keeping the Model "as immutable as possible".  To be specific, here is a small piece of code that implements MVC in imperative Java (see below).   How would this same problem be solved in a pure functional language, or only using purely functional aspects of Scala?  Would a new Model be created each time setState is called?  If so, how would the View be notified about this?  What if JFrames and other GUI elements were immutable, would they be recreated with the new correct state each time there is a model change?  Or is this problem too awkward to handle elegantly with functional programming, and  imperative programming + mutable Model (& View JFrame) is better?

Thanks,
Sam Reid

class Model {
        int state;
        ArrayList listeners;
        void setState( int state ) {this.state = state;
            for ( int i = 0; i < listeners.size(); i++ ) {
                ((Listener) listeners.get( i )).modelChanged();
            }
        }
        int getState() {return state;}
        void addListener(Listener listener){listeners.add(listener);}
    }
    interface Listener{
        void modelChanged();
    }
    class Controller {
        Model model;
        Controller( Model model ) {this.model = model;}
        void incrementModel() {model.setState( model.getState()+1);}
    }
    class View{
        Model model;
        JFrame frame;
        View( final Model model ) {
            this.model = model;
            model.addListener(new Listener(){
                public void modelChanged(){
                    frame.setSize( model.getState(),model.getState() );
                }
            });
        }
    }

David Pollak wrote:
Sam,
Scala does very well in the MVC paradigm (I'm talk real Smalltalk style MVC, not the pseudo web MVC that Rails and Struts purport to have).
Passing immutable data structures makes multithreaded coding a lot simpler.  You know the events that your MVC code receives won't be mutated out from under you.
Scala's Actors provide a very nice way to do MVC.  But you can be a little more type-safe and use functions or partial functions as parameters for your listeners.
Thanks,
David  

On Sat, Jan 3, 2009 at 7:43 PM, Samuel Robert Reid <Reids [at] colorado [dot] edu> wrote:
Scala Community,

I have a problem that I would normally solve using the model-view-controller paradigm with imperative/procedural code, and was wondering how this type of problem could be addressed with functional programming, particularly with respect to immutable objects.  What does a functional programmer do for mvc type problems?

Thanks,
Sam Reid



Raoul Duke
Joined: 2009-01-05,
User offline. Last seen 42 years 45 weeks ago.
Re: MVC in functional programming

> It's possible to get rid of vars if you really want to, though I think
> David's original code is preferable by far:

i'm curious how people decide to prefer either Erlang style
tail-recursion-looping, or more imperative val approaches. what are
your thoughts? thank you.

David Pollak
Joined: 2008-12-16,
User offline. Last seen 42 years 45 weeks ago.
Re: MVC in functional programming


On Mon, Jan 5, 2009 at 10:48 AM, Raoul Duke <raould [at] gmail [dot] com> wrote:
> It's possible to get rid of vars if you really want to, though I think
> David's original code is preferable by far:

i'm curious how people decide to prefer either Erlang style
tail-recursion-looping, or more imperative val approaches. what are
your thoughts? thank you.

If I'm going to pass more than 2 pieces of "state" around, I'll use private vars. 


--
Lift, the simply functional web framework http://liftweb.net
Collaborative Task Management http://much4.us
Follow me: http://twitter.com/dpp
Git some: http://github.com/dpp
Ricky Clarkson
Joined: 2008-12-19,
User offline. Last seen 3 years 2 weeks ago.
Re: MVC in functional programming
I'll normally wait for an abstraction to fall out.  If I'm passing two bits of state around I'm probably missing an opportunity to use foldLeft or something.

2009/1/5 David Pollak <feeder [dot] of [dot] the [dot] bears [at] gmail [dot] com>


On Mon, Jan 5, 2009 at 10:48 AM, Raoul Duke <raould [at] gmail [dot] com> wrote:
> It's possible to get rid of vars if you really want to, though I think
> David's original code is preferable by far:

i'm curious how people decide to prefer either Erlang style
tail-recursion-looping, or more imperative val approaches. what are
your thoughts? thank you.

If I'm going to pass more than 2 pieces of "state" around, I'll use private vars. 


--
Lift, the simply functional web framework http://liftweb.net
Collaborative Task Management http://much4.us
Follow me: http://twitter.com/dpp
Git some: http://github.com/dpp

mtopol
Joined: 2009-01-12,
User offline. Last seen 42 years 45 weeks ago.
Re: MVC in functional programming

The most elegant purely functional way to pass immutable state around as a
function argument is Haskell's approach with state-transforming monads. But
in a non-pure functional language like Scala it would probably not be worth
the effort. In Haskell there are special language constructs that make the
monad-using code look ok.

Raoul Duke wrote:
>
> i'm curious how people decide to prefer either Erlang style
> tail-recursion-looping, or more imperative val approaches. what are
> your thoughts? thank you.
>

Tony Morris
Joined: 2008-12-19,
User offline. Last seen 30 weeks 4 days ago.
Re: MVC in functional programming

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

mtopol wrote:
> In Haskell there are special language constructs that make the
> monad-using code look ok.
>
So does Scala, though it is not type-safe as in Haskell. Take a look
at for-comprehensions.
Here is the state monad:
http://blog.tmorris.net/the-state-monad-for-scala-users/

- --
Tony Morris
http://tmorris.net/

S, K and I ought to be enough for anybody.

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.6 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQFJawhKmnpgrYe6r60RAq5NAJ4684W9PfeRuuwuoh+gCZ4OFgctugCgsA+u
XfVH+ouNZeJGh9U3lp87wF8=
=gvyC
-----END PGP SIGNATURE-----

mtopol
Joined: 2009-01-12,
User offline. Last seen 42 years 45 weeks ago.
Re: MVC in functional programming

Interesting... so, where in Haskell we have a List as a kind of Monad, in
Scala we can have a State (or any other) monad as a kind of List and use
for-comprehension to help with the bind operation. Not as elegant, but seems
to work nicely. I need to look into Scalaz much more...

tmorris wrote:
>
>> In Haskell there are special language constructs that make the
>> monad-using code look ok.
>>
> So does Scala, though it is not type-safe as in Haskell. Take a look
> at for-comprehensions.
> Here is the state monad:
> http://blog.tmorris.net/the-state-monad-for-scala-users/
>

Raoul Duke
Joined: 2009-01-05,
User offline. Last seen 42 years 45 weeks ago.
Re: MVC in functional programming

> The most elegant purely functional way to pass immutable state around as a
> function argument is Haskell's approach with state-transforming monads.

(getting OT from Scala, but... i have been trying to learn monads, and
have sort of made some headway, but i do find the composition of
monads to be kinda confusing and a pain in haskell syntax, so far.

i have to wonder if effects typing (e.g. DDC) or uniqueness (e.g.
Clean) or linear types (?) are a better way to get at these issues, at
least from a usability perspective.

sincerely.)

James Iry
Joined: 2008-08-19,
User offline. Last seen 1 year 23 weeks ago.
Re: MVC in functional programming
No, state is a kind of monad, not a kind of list.  It's just that Scala has a take on monad comprehensions that looks listy.  See Wadler's "Comprehending Monads" for an explanation of the basic idea of generalizing list comprehensions to all monads

On Mon, Jan 12, 2009 at 4:19 AM, mtopol <mt4web [at] gmail [dot] com> wrote:

Interesting... so, where in Haskell we have a List as a kind of Monad, in
Scala we can have a State (or any other) monad as a kind of List and use
for-comprehension to help with the bind operation. Not as elegant, but seems
to work nicely. I need to look into Scalaz much more...


tmorris wrote:
>
>> In Haskell there are special language constructs that make the
>> monad-using code look ok.
>>
> So does Scala, though it is not type-safe as in Haskell. Take a look
> at for-comprehensions.
> Here is the state monad:
> http://blog.tmorris.net/the-state-monad-for-scala-users/
>

--
View this message in context: http://www.nabble.com/-scala--MVC-in-functional-programming-tp21272732p21413378.html
Sent from the Scala mailing list archive at Nabble.com.


Jesper Nordenberg
Joined: 2008-12-27,
User offline. Last seen 42 years 45 weeks ago.
Re: MVC in functional programming

(moving to debate)

Raoul Duke wrote:
>> The most elegant purely functional way to pass immutable state around as a
>> function argument is Haskell's approach with state-transforming monads.
>
> (getting OT from Scala, but... i have been trying to learn monads, and
> have sort of made some headway, but i do find the composition of
> monads to be kinda confusing and a pain in haskell syntax, so far.
>
> i have to wonder if effects typing (e.g. DDC) or uniqueness (e.g.
> Clean) or linear types (?) are a better way to get at these issues, at
> least from a usability perspective.

The problem with modeling side effects, errors, state etc. using monads
is that they get intertwined in a nested structure, when a flat set
model would be a better fit. For example, if you have a function that
can "throw" two types of errors, it's very inconvenient (at least in
Scala, for many reasons) to model it as ValueOrError[Result,
Either[ErrorA, ErrorB]]. In Java you can easily handle this as the
thrown exceptions is declared as a set orthogonal to the function return
type. This require more compiler logic, but is much more practical to
use. Similar compiler logic can be added to handle function purity and
state, which have the same problems of nested monad structures.

I'm certain that there are type systems powerful enough to model type
sets in a practically useful way, but AFAIK Scala's is not powerful
enough to do this.

/Jesper Nordenberg

mtopol
Joined: 2009-01-12,
User offline. Last seen 42 years 45 weeks ago.
Re: MVC in functional programming

Thanks for the pointer, this is all very interesting. So what you're saying
is that in Scala we should look at Iterable as not primarily a kind of
sequence, but as a monad, and at flatMap not as a function on lists, but as
the general bind operation on monads. This generalization from list to monad
is what I find less elegant than Haskell's specialization of Monad to List.
On the other hand, it's probably less "hard-core" and intimidating to people
migrating from something like Java to functional programming.

James Iry-2 wrote:
>
> No, state is a kind of monad, not a kind of list. It's just that Scala
> has
> a take on monad comprehensions that looks listy. See Wadler's
> "Comprehending Monads" for an explanation of the basic idea of
> generalizing
> list comprehensions to all monads
>

Jesper Nordenberg
Joined: 2008-12-27,
User offline. Last seen 42 years 45 weeks ago.
Re: MVC in functional programming

mtopol wrote:
> Thanks for the pointer, this is all very interesting. So what you're saying
> is that in Scala we should look at Iterable as not primarily a kind of
> sequence, but as a monad, and at flatMap not as a function on lists, but as
> the general bind operation on monads. This generalization from list to monad
> is what I find less elegant than Haskell's specialization of Monad to List.

No, you misunderstand. The Iterable interface/trait has nothing to do
with Scala's builtin for-syntax, any object implementing the flatMap,
map and filter methods can be used in a for-construct (the methods don't
even have to have the correct "monadic" type signatures as there is no
common super type defining them).

/Jesper Nordenberg

mtopol
Joined: 2009-01-12,
User offline. Last seen 42 years 45 weeks ago.
Re: Re: MVC in functional programming

Exactly, I stand corrected. Tony, is this what you meant when you said that
Scalaz's State is not type-safe as in Haskell?

As far as I can see, the object is not required to implement filter unless
you use an "if" guard. Also, a monad should only need one bind operation,
but in Scala it appears that both map and flatMap are necessary. This aspect
is still not entirely clear to me.

Jesper Nordenberg wrote:
>
> No, you misunderstand. The Iterable interface/trait has nothing to do
> with Scala's builtin for-syntax, any object implementing the flatMap,
> map and filter methods can be used in a for-construct (the methods don't
> even have to have the correct "monadic" type signatures as there is no
> common super type defining them).
>
> /Jesper Nordenberg
>
>
>

James Iry
Joined: 2008-08-19,
User offline. Last seen 1 year 23 weeks ago.
Re: Re: MVC in functional programming
The challenge is that in a standard OO style there no way to useful way to specify unit on an interface.  While foo.map and foo.flatMap make sense, foo.unit makes much less sense. 

But it turns out that if you have both map and bind then you can do useful monad comprehensions without requiring unit because

m map f == m flatMap {x => unit(f(x)}  // Scala
fmap f m == m >>= \x -> return $ f x -- Haskell

So in Haskell where you write
do
   x1 <- exp1
   x2 <- exp2
   return exp3

Which translates to
exp1 >>= \x1 -> exp2 >>= \x2 -> return exp3

In Scala you write

for {
  x1 <- exp1
  x2 <- exp2
} yield exp3

Which translates to

exp1 flatMap {x1 => exp2 map {x2 => exp3}}

As for filter,  you have to have it if you use an "if" guard or if you use refutable pattern matching

for {(x,2) <- List((1,2),(2,2),(3,1))} yield x // Translates into something based on filter. 

Note that Haskell is very similar in the fact that the Monad type class requires "fail" even though not all monads have zeros.  Filter and fail are related because

m filter p == m flatMap {x => if(p(x)) unit(x) else fail}  // Scala
mfilter p m == m >>= \x -> if p x then return x else fail -- Haskell

On Tue, Jan 13, 2009 at 4:39 AM, mtopol <mt4web [at] gmail [dot] com> wrote:

Exactly, I stand corrected. Tony, is this what you meant when you said that
Scalaz's State is not type-safe as in Haskell?

As far as I can see, the object is not required to implement filter unless
you use an "if" guard. Also, a monad should only need one bind operation,
but in Scala it appears that both map and flatMap are necessary. This aspect
is still not entirely clear to me.


Jesper Nordenberg wrote:
>
> No, you misunderstand. The Iterable interface/trait has nothing to do
> with Scala's builtin for-syntax, any object implementing the flatMap,
> map and filter methods can be used in a for-construct (the methods don't
> even have to have the correct "monadic" type signatures as there is no
> common super type defining them).
>
> /Jesper Nordenberg
>
>
>

--
View this message in context: http://www.nabble.com/-scala--MVC-in-functional-programming-tp21272732p21434954.html
Sent from the Scala mailing list archive at Nabble.com.


Tony Morris
Joined: 2008-12-19,
User offline. Last seen 30 weeks 4 days ago.
Re: Re: MVC in functional programming

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

mtopol wrote:
> Exactly, I stand corrected. Tony, is this what you meant when you said that
> Scalaz's State is not type-safe as in Haskell?
Hello, no I meant that Scala's for-comprehensions (roughly equivalent
to Haskell's do-notation) is not type-safe. Specifically you don't
have to implement a common interface to be used in the
for-comprehension. I imagine that this is because at the time, higher
kinds were not available. In Haskell, to use do-notation, the type
constructor must have a Monad instance.

Note that a hypothetical Monad instance is not enough to use Scala's
for-comprehensions. You also need a MonadPlus/Zero if you are going to
use the filter method.

Here is some more reading on this topic if you like:
http://blog.tmorris.net/type-safe-scala-sequence-comprehensions/

I hope this helps.

- --
Tony Morris
http://tmorris.net/

S, K and I ought to be enough for anybody.

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.6 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQFJbQNpmnpgrYe6r60RAoJYAJ9GMCXaFBfqeghsW4qgpem8YfSfiwCfaPiM
a2ao8tN4rJ7neXX7D+eoaM0=
=3spR
-----END PGP SIGNATURE-----

milessabin
Joined: 2008-08-11,
User offline. Last seen 33 weeks 3 days ago.
Re: Re: MVC in functional programming

On Tue, Jan 13, 2009 at 9:11 PM, Tony Morris wrote:
> Hello, no I meant that Scala's for-comprehensions (roughly equivalent
> to Haskell's do-notation) is not type-safe.

This is complete and utter nonsense because ...

> Specifically you don't have to implement a common interface to be used in the
> for-comprehension

... this is not a criterion of type-safety (of for comprehensions, or
anything else for that matter).

Cheers,

Miles

Miles Sabin
tel: +44 (0)1273 720 779
mobile: +44 (0)7813 944 528
skype: milessabin

Tony Morris
Joined: 2008-12-19,
User offline. Last seen 30 weeks 4 days ago.
Re: Re: MVC in functional programming

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Miles Sabin wrote:
> On Tue, Jan 13, 2009 at 9:11 PM, Tony Morris
> wrote:
>> Hello, no I meant that Scala's for-comprehensions (roughly
>> equivalent to Haskell's do-notation) is not type-safe.
>
> This is complete and utter nonsense because ...

scala> case class X[+A](x: List[A]) { def map[B](f: String => Int):
Int = 7 }
defined class X

scala> for(z <- X(List(1, 2, 3))) yield 5 // yay!
res0: Int = 7

>
>> Specifically you don't have to implement a common interface to be
>> used in the for-comprehension
>
> ... this is not a criterion of type-safety (of for comprehensions,
> or anything else for that matter).
Nobody said it was.

>
> Cheers,
>
>
> Miles
>
> Miles Sabin tel: +44 (0)1273 720 779 mobile: +44 (0)7813 944 528
> skype: milessabin
>
>
>
- --
Tony Morris
http://tmorris.net/

S, K and I ought to be enough for anybody.

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.6 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQFJbSuhmnpgrYe6r60RAu0kAKCxzCJUzGYR7EOGlXnnCB5/c+5JqgCgmK6e
uAZmFffM3tmsFDFxCRPY+4Q=
=UAt7
-----END PGP SIGNATURE-----

Sean McDirmid
Joined: 2008-12-17,
User offline. Last seen 42 years 45 weeks ago.
Re: Re: MVC in functional programming
Scala for-comprehension are just syntactic sugar. It is not a very real language constructs since the compiler will not report error messages in terms of for comprehensions, but rather the map/filter/flatMap calls it de-sugars into. To say it is type safe or not is not very meaningful (of course, the translation is run through the type checker, so its safe), but to say for comprehensions are not modular with respect to their translation is reasonable (since code is checked after, not before, macro expansion). On the other hand, for translation is very simple, and most non-new users will be able to map the error messages back to what they actually wrote.  
I personally gave up on for comprehensions a while ago: writing down map/filter/flatMap is more clear and often requires less typing. For doesn't add much to the code (nor does it detract much).
On Wed, Jan 14, 2009 at 8:02 AM, Tony Morris <tmorris [at] tmorris [dot] net> wrote:
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1



Miles Sabin wrote:
> On Tue, Jan 13, 2009 at 9:11 PM, Tony Morris <tmorris [at] tmorris [dot] net>
> wrote:
>> Hello, no I meant that Scala's for-comprehensions (roughly
>> equivalent to Haskell's do-notation) is not type-safe.
>
> This is complete and utter nonsense because ...

scala> case class X[+A](x: List[A]) { def map[B](f: String => Int):
Int = 7 }
defined class X

scala> for(z <- X(List(1, 2, 3))) yield 5 // yay!
res0: Int = 7

>
>> Specifically you don't have to implement a common interface to be
>> used in the for-comprehension
>
> ... this is not a criterion of type-safety (of for comprehensions,
> or anything else for that matter).
Nobody said it was.

>
> Cheers,
>
>
> Miles
>
> Miles Sabin tel:    +44 (0)1273 720 779 mobile: +44 (0)7813 944 528
>  skype:  milessabin
>
>
>
- --
Tony Morris
http://tmorris.net/

S, K and I ought to be enough for anybody.

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.6 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQFJbSuhmnpgrYe6r60RAu0kAKCxzCJUzGYR7EOGlXnnCB5/c+5JqgCgmK6e
uAZmFffM3tmsFDFxCRPY+4Q=
=UAt7
-----END PGP SIGNATURE-----


Dave Griffith
Joined: 2009-01-14,
User offline. Last seen 42 years 45 weeks ago.
Re: Re: MVC in functional programming

The for-comprehensions remind me of the difference between relational
algebra and relational calculus. Relational algebra is clear and extremely
precise once you know it, but relational calculus is a lot more intuitive,
particularly for naive users.

If compile-time errors are reported for for-comprehensions in terms of
map/filter/flatMap calls, that would seem to be a pretty serious usability
bug. Surprised I haven't hit it yet.

Sean McDirmid wrote:
>
> Scala for-comprehension are just syntactic sugar. It is not a very real
> language constructs since the compiler will not report error messages in
> terms of for comprehensions, but rather the map/filter/flatMap calls it
> de-sugars into.
>

Sean McDirmid
Joined: 2008-12-17,
User offline. Last seen 42 years 45 weeks ago.
Re: Re: MVC in functional programming
This is easy: just write some simple overloading with ambiguous map methods, or provide the wrong expected type in a yield, or don't provide the implicit parameter of your map method. All of these will cause for to fail type checking in a way that requires you to know that it translates into the tree "map(f)" where the type checker then operators on this tree. This is definitely a usability problem for new users, and requires precise knowledge of how for is translated to debug the type errors. Fortunately, for translation is pretty simple and easy to remember, but then if the translation is simple, I wonder what the point is. 
On Wed, Jan 14, 2009 at 9:12 AM, Dave Griffith <dave [dot] l [dot] griffith [at] gmail [dot] com> wrote:


The for-comprehensions remind me of the difference between relational
algebra and relational calculus.  Relational algebra is clear and extremely
precise once you know it, but relational calculus is a lot more intuitive,
particularly for naive users.

If compile-time errors are reported for for-comprehensions in terms of
map/filter/flatMap calls, that would seem to be a pretty serious usability
bug.  Surprised I haven't hit it yet.


Sean McDirmid wrote:
>
> Scala for-comprehension are just syntactic sugar. It is not a very real
> language constructs since the compiler will not report error messages in
> terms of for comprehensions, but rather the map/filter/flatMap calls it
> de-sugars into.
>

--
View this message in context: http://www.nabble.com/-scala--MVC-in-functional-programming-tp21272732p21448180.html
Sent from the Scala mailing list archive at Nabble.com.


mtopol
Joined: 2009-01-12,
User offline. Last seen 42 years 45 weeks ago.
Re: Re: MVC in functional programming

The rules of transformation may be simple, but that doesn't say anything
about what "for" does to code readability. The way I see it, and having
Haskell's "do" in mind, "for" syntax converts nested terms into chained
terms. I see this as a big advantage once we get past the simplest cases.
There are also other advantages: less boilerplate tokens, less rules to
remember about which methods to use, and so on. Some of these are more
useful to beginners than veterans, but some stay useful even later on.

Sean McDirmid wrote:
>
> Fortunately, for translation is pretty simple and easy to remember, but
> then if the
> translation is simple, I wonder what the point is.
>

Sean McDirmid
Joined: 2008-12-17,
User offline. Last seen 42 years 45 weeks ago.
Re: Re: MVC in functional programming
I don't know. I just gave up on for after debugging one too many type errors that were obscured by the for comprehension. I prefer increased productivity over better code readability. For is like any other macro, it might make the code look nicer, but at the same time its a bit dangerous and can distract you from where your problems really are. 

On Wed, Jan 14, 2009 at 4:47 PM, mtopol <mt4web [at] gmail [dot] com> wrote:

The rules of transformation may be simple, but that doesn't say anything
about what "for" does to code readability. The way I see it, and having
Haskell's "do" in mind, "for" syntax converts nested terms into chained
terms. I see this as a big advantage once we get past the simplest cases.
There are also other advantages: less boilerplate tokens, less rules to
remember about which methods to use, and so on. Some of these are more
useful to beginners than veterans, but some stay useful even later on.


Sean McDirmid wrote:
>
> Fortunately, for translation is pretty simple and easy to remember, but
> then if the
> translation is simple, I wonder what the point is.
>

--
View this message in context: http://www.nabble.com/-scala--MVC-in-functional-programming-tp21272732p21452022.html
Sent from the Scala mailing list archive at Nabble.com.


mtopol
Joined: 2009-01-12,
User offline. Last seen 42 years 45 weeks ago.
Re: Re: MVC in functional programming

According to [1] there is work in progress on using Iterable improved through
the introduction of higher-kinded types "to type-check for-comprehensions
without first expanding them to the corresponding method calls".

[1] http://www.cs.kuleuven.be/~adriaan/files/higher.pdf

Sean McDirmid wrote:
>
> I don't know. I just gave up on for after debugging one too many type
> errors
> that were obscured by the for comprehension. I prefer increased
> productivity
> over better code readability. For is like any other macro, it might make
> the
> code look nicer, but at the same time its a bit dangerous and can distract
> you from where your problems really are.
>

Dave Griffith
Joined: 2009-01-14,
User offline. Last seen 42 years 45 weeks ago.
Re: Re: MVC in functional programming

FWIW, I'm (finally) in the process of creating an IntelliJ IDEA plugin of
inspections/intentions/refactoring/templates for Scala. Among the
intentions will be some for automatically converting for loops into
filter/map/flatmap chains, and (where possible) vice versa. Also some nice
ones for merging nested loops into single loops (and vice versa), turning
loop guards into nested ifs, etc. Experienced Scala programmers might not
need it, but it should simplify the Java->Scala learning curve.

--Dave Grifith

Tony Morris
Joined: 2008-12-19,
User offline. Last seen 30 weeks 4 days ago.
Re: Re: MVC in functional programming

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Hi Dave,
That's excellent news. Is this done in collaboration with JetBrains
somehow or your own endeavour? How will it integrate with the existing
plugin or is this not really an issue? I'm not familiar with IDEA
plugins, so excuse my ignorance - I am very curious however.

Dave Griffith wrote:
> FWIW, I'm (finally) in the process of creating an IntelliJ IDEA
> plugin of inspections/intentions/refactoring/templates for Scala.
> Among the intentions will be some for automatically converting for
> loops into filter/map/flatmap chains, and (where possible) vice
> versa. Also some nice ones for merging nested loops into single
> loops (and vice versa), turning loop guards into nested ifs, etc.
> Experienced Scala programmers might not need it, but it should
> simplify the Java->Scala learning curve.
>
> --Dave Grifith

- --
Tony Morris
http://tmorris.net/

S, K and I ought to be enough for anybody.

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.6 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQFJbmB2mnpgrYe6r60RAlEUAJ95Kw6tOtXx6dTblsbm9sjPB8HI/gCeLI6N
q57ezlToAZhqMdL9wGmuORg=
=ADj5
-----END PGP SIGNATURE-----

Dave Griffith
Joined: 2009-01-14,
User offline. Last seen 42 years 45 weeks ago.
Re: Re: MVC in functional programming

For now, this one is one my own, but I have collaborated with JetBrains in
the past. Several of my intention/inspection/refactoring plugins have
eventually been integrated into the core IDEA distribution, including most
of the Java, JavaScript, and Groovy intentions and inspections currently
shipping. It's certainly possible that the same will occur with
ScalaPowerPack, as I'm calling this one. This plugin will complement the
existing Scala plugin, relying on it for parsing and type information. As
soon as I get a bit farther along, I'll post a features roadmap here, and
would love to hear comments.

Samuel Robert Reid
Joined: 2008-12-17,
User offline. Last seen 1 year 22 weeks ago.
Re: Re: MVC in functional programming

Dave,

I'd be very happy to see IntelliJ IDEA templates for creation of main
and for println. Let me know how it goes.

Sam Reid

Dave Griffith wrote:
> FWIW, I'm (finally) in the process of creating an IntelliJ IDEA plugin of
> inspections/intentions/refactoring/templates for Scala. Among the
> intentions will be some for automatically converting for loops into
> filter/map/flatmap chains, and (where possible) vice versa. Also some nice
> ones for merging nested loops into single loops (and vice versa), turning
> loop guards into nested ifs, etc. Experienced Scala programmers might not
> need it, but it should simplify the Java->Scala learning curve.
>
> --Dave Grifith
>

Copyright © 2012 École Polytechnique Fédérale de Lausanne (EPFL), Lausanne, Switzerland