- About Scala
- Documentation
- Code Examples
- Software
- Scala Developers
functional newbie, domain entities
Wed, 2009-04-08, 20:06
Hello list,
I'm getting into Scala, coming from a primarily Java background (with
lots of JS, some Ruby, and a few others in the mix). As expected, some
of the more exotic parts of the syntax are a bit confusing, but overall
I really like it. Most of that confusion has to do with my newness to
some of the core focuses of functional programming. It's not that the
syntax is cryptic, it's that some of the concepts are new (or rather,
newish).
One pragmatic issue I'm having is with the concept of immutability. It's
conceptually simple, and I've created many immutable classes
intentionally in other languages. There are some areas however, where I
don't see how a class stands to gain from immutability (or how it could
even be so in context). Consider a typical enterprise application, where
something like hibernate would be involved. Such entities are almost
always riddled with getters/setters, which, apart from being hideous,
are obviously mutable.
I guess my question then if for people using Scala in this context. Does
it make sense for entity classes to be immutable? What are the points to
consider when answering this? One classic example would be a user
preferences screen, where a user can update their personal information.
Hibernate yields a persistent instance (bound to a session), and it
needs to be updated. Can/should a new instance be derived from this (ie,
modification via derivation and constructor injection)?
Pardon the onslaught, and thanks for your input. I'm enjoying Scala very
much and want to use it for real code, but I want to learn new tricks
(that is, I'm not looking for a shorter Java).
-chris
Wed, 2009-04-08, 21:57
#2
Re: functional newbie, domain entities
Nils Kilden-Pedersen wrote:
class User(val id: Long, val firstName: String, val lastName: String, val emailAddress: String)
Now assuming that an entity w/ idi 1 exists in the database, and that hibernate has been configured, AND we have a Session available as session, we can load the instance:
val u = session.load("User", 1)
Problem 1: Hibernate instantiates entities using a no-arg constructor, and then sets properties either via field or setter access. That's a "problem" of hibernate, but I'm curious how Scala users would deal with it.
Next up, changing the persistent data of that instance. Since User is immutable (val members only), we obviously can't say u.frstName = "Bill". So, we need some factory methods to do some derivation instantiation.
object User {
def modFirstName(u: User, firstName: String) = new User(u.id, firstName, u.lastName, u.emailAddress)
}
val u1 = User.modFirstName(u, "Bill")
Problem 2: I need to reference this new instance, but because I'm going full-on immutable, I can't (and I get this error on the REPL: <console>:9: error: recursive value u needs type val u = User.modFirstName(u, "Bill"))
Problem 3: Pretending problem 2 didn't exist, I've got a maintenance nightmare. If modifications mean new instances, then for every possible modification, or combination of modifications, I need a factory derivation method - or do some sketchy reflection. Yikes! I hope I'm missing something here...
Problem 4: Again ignoring problems 2 and 3, and assuming I've got the modification-by-derivation under control, the ORM knows about the original one; the one load()ed from the database. So how can this be dealt with? In hibernate I could do session.evict(u), and then /probably/ use session.update(u1) or maybe session.persist(u1) (needs testing), but I'm not sure about other ORMs.
Thanks tons for your input, and I'm sorry to bombard you with questions. As I said, I'm learning to think immutably, but for things like domain entity management I'm hitting some conceptual walls.
-chris
4a9de6980904081241q5dabf16eh180ee80f76a2cb59 [at] mail [dot] gmail [dot] com" type="cite"> On Wed, Apr 8, 2009 at 2:06 PM, Chris Lewis <chris [at] thegodcode [dot] net" rel="nofollow">chris@thegodcode.net> wrote:Yeah, and it's easy to imagine scenarios with simpler things like java.lang.String. But for ORM layers, like hibernate, how would it work? It's a given that data in a database must change - at least in certain applications (like my user prefs example). So there are several concerns here with immutability. First, and overly simplified entity class:
Does it make sense for entity classes to be immutable?
Ask it the other way around. Does it make sense for them to be mutable?
Having them be immutable, caching becomes infinitely easier and safer.
class User(val id: Long, val firstName: String, val lastName: String, val emailAddress: String)
Now assuming that an entity w/ idi 1 exists in the database, and that hibernate has been configured, AND we have a Session available as session, we can load the instance:
val u = session.load("User", 1)
Problem 1: Hibernate instantiates entities using a no-arg constructor, and then sets properties either via field or setter access. That's a "problem" of hibernate, but I'm curious how Scala users would deal with it.
Next up, changing the persistent data of that instance. Since User is immutable (val members only), we obviously can't say u.frstName = "Bill". So, we need some factory methods to do some derivation instantiation.
object User {
def modFirstName(u: User, firstName: String) = new User(u.id, firstName, u.lastName, u.emailAddress)
}
val u1 = User.modFirstName(u, "Bill")
Problem 2: I need to reference this new instance, but because I'm going full-on immutable, I can't (and I get this error on the REPL: <console>:9: error: recursive value u needs type val u = User.modFirstName(u, "Bill"))
Problem 3: Pretending problem 2 didn't exist, I've got a maintenance nightmare. If modifications mean new instances, then for every possible modification, or combination of modifications, I need a factory derivation method - or do some sketchy reflection. Yikes! I hope I'm missing something here...
Problem 4: Again ignoring problems 2 and 3, and assuming I've got the modification-by-derivation under control, the ORM knows about the original one; the one load()ed from the database. So how can this be dealt with? In hibernate I could do session.evict(u), and then /probably/ use session.update(u1) or maybe session.persist(u1) (needs testing), but I'm not sure about other ORMs.
Thanks tons for your input, and I'm sorry to bombard you with questions. As I said, I'm learning to think immutably, but for things like domain entity management I'm hitting some conceptual walls.
-chris
Wed, 2009-04-08, 22:37
#3
Re: functional newbie, domain entities
On Wed, Apr 8, 2009 at 1:52 PM, Chris Lewis wrote:
> Nils Kilden-Pedersen wrote:
>
> On Wed, Apr 8, 2009 at 2:06 PM, Chris Lewis wrote:
>>
>> Does it make sense for entity classes to be immutable?
>
> Ask it the other way around. Does it make sense for them to be mutable?
>
> Having them be immutable, caching becomes infinitely easier and safer.
>
> Yeah, and it's easy to imagine scenarios with simpler things like
> java.lang.String. But for ORM layers, like hibernate, how would it work?
> It's a given that data in a database must change - at least in certain
> applications (like my user prefs example). So there are several concerns
> here with immutability. First, and overly simplified entity class:
>
> class User(val id: Long, val firstName: String, val lastName: String, val
> emailAddress: String)
>
> Now assuming that an entity w/ idi 1 exists in the database, and that
> hibernate has been configured, AND we have a Session available as session,
> we can load the instance:
>
> val u = session.load("User", 1)
>
> Problem 1: Hibernate instantiates entities using a no-arg constructor, and
> then sets properties either via field or setter access. That's a "problem"
> of hibernate, but I'm curious how Scala users would deal with it.
Take a look at
http://www.scala-lang.org/docu/files/api/scala/reflect/BeanProperty.html
I know nothing about it beyond its existence though...
>
> Next up, changing the persistent data of that instance. Since User is
> immutable (val members only), we obviously can't say u.frstName = "Bill".
> So, we need some factory methods to do some derivation instantiation.
>
> object User {
> def modFirstName(u: User, firstName: String) = new User(u.id, firstName,
> u.lastName, u.emailAddress)
> }
> val u1 = User.modFirstName(u, "Bill")
>
> Problem 2: I need to reference this new instance, but because I'm going
> full-on immutable, I can't (and I get this error on the REPL: :9:
> error: recursive value u needs type val u = User.modFirstName(u, "Bill"))
because the name 'u' is bound to the lhs. Scala allows for recursive
declarations, but only if you give the type. You'll need to use
another name
val oldU = u;
val u = User.modFirstName(oldU,"Bill");
>
> Problem 3: Pretending problem 2 didn't exist, I've got a maintenance
> nightmare. If modifications mean new instances, then for every possible
> modification, or combination of modifications, I need a factory derivation
> method - or do some sketchy reflection. Yikes! I hope I'm missing something
> here...
>
> Problem 4: Again ignoring problems 2 and 3, and assuming I've got the
> modification-by-derivation under control, the ORM knows about the original
> one; the one load()ed from the database. So how can this be dealt with? In
> hibernate I could do session.evict(u), and then /probably/ use
> session.update(u1) or maybe session.persist(u1) (needs testing), but I'm not
> sure about other ORMs.
>
>
> Thanks tons for your input, and I'm sorry to bombard you with questions. As
> I said, I'm learning to think immutably, but for things like domain entity
> management I'm hitting some conceptual walls.
>
> -chris
Thu, 2009-04-09, 00:57
#4
Re: functional newbie, domain entities
"But for ORM layers, like hibernate"
So your question is: for object-relational mapping layers, how does functional programming work? It isn't even involved. Abstract around the SQL queries, rather than around mutable objects that abstract around SQL queries, if you want to involve functional programming.
2009/4/8 Chris Lewis <chris@thegodcode.net>
So your question is: for object-relational mapping layers, how does functional programming work? It isn't even involved. Abstract around the SQL queries, rather than around mutable objects that abstract around SQL queries, if you want to involve functional programming.
2009/4/8 Chris Lewis <chris@thegodcode.net>
Nils Kilden-Pedersen wrote:On Wed, Apr 8, 2009 at 2:06 PM, Chris Lewis <chris@thegodcode.net> wrote:Yeah, and it's easy to imagine scenarios with simpler things like java.lang.String. But for ORM layers, like hibernate, how would it work? It's a given that data in a database must change - at least in certain applications (like my user prefs example). So there are several concerns here with immutability. First, and overly simplified entity class:
Does it make sense for entity classes to be immutable?
Ask it the other way around. Does it make sense for them to be mutable?
Having them be immutable, caching becomes infinitely easier and safer.
class User(val id: Long, val firstName: String, val lastName: String, val emailAddress: String)
Now assuming that an entity w/ idi 1 exists in the database, and that hibernate has been configured, AND we have a Session available as session, we can load the instance:
val u = session.load("User", 1)
Problem 1: Hibernate instantiates entities using a no-arg constructor, and then sets properties either via field or setter access. That's a "problem" of hibernate, but I'm curious how Scala users would deal with it.
Next up, changing the persistent data of that instance. Since User is immutable (val members only), we obviously can't say u.frstName = "Bill". So, we need some factory methods to do some derivation instantiation.
object User {
def modFirstName(u: User, firstName: String) = new User(u.id, firstName, u.lastName, u.emailAddress)
}
val u1 = User.modFirstName(u, "Bill")
Problem 2: I need to reference this new instance, but because I'm going full-on immutable, I can't (and I get this error on the REPL: <console>:9: error: recursive value u needs type val u = User.modFirstName(u, "Bill"))
Problem 3: Pretending problem 2 didn't exist, I've got a maintenance nightmare. If modifications mean new instances, then for every possible modification, or combination of modifications, I need a factory derivation method - or do some sketchy reflection. Yikes! I hope I'm missing something here...
Problem 4: Again ignoring problems 2 and 3, and assuming I've got the modification-by-derivation under control, the ORM knows about the original one; the one load()ed from the database. So how can this be dealt with? In hibernate I could do session.evict(u), and then /probably/ use session.update(u1) or maybe session.persist(u1) (needs testing), but I'm not sure about other ORMs.
Thanks tons for your input, and I'm sorry to bombard you with questions. As I said, I'm learning to think immutably, but for things like domain entity management I'm hitting some conceptual walls.
-chris
Thu, 2009-04-09, 02:17
#5
Re: functional newbie, domain entities
Ricky Clarkson wrote:
>
> "But for ORM layers, like hibernate"
> So your question is: for object-relational mapping layers, how does
> functional programming work? It isn't even involved. Abstract around the
> SQL queries, rather than around mutable objects that abstract around SQL
> queries, if you want to involve functional programming.
>
Ricky,
You've made an interesting point - what would help me is some elaboration
about what abstracting around SQL queries means, or perhaps an example?
Thanks - and thanks Chris for asking an interesting question!
Cheers,
Dan
Thu, 2009-04-09, 04:37
#6
Re: functional newbie, domain entities
Ricky Clarkson wrote:
7eeb06460904081641u5ad5023dx6156e7b0a3919565 [at] mail [dot] gmail [dot] com" type="cite">"But for ORM layers, like hibernate"A little more specific; how does the mantra of object immutability mesh with ORM implementations? I guess my question was a bit too narrow in that it focused on Hibernate, but given that most if not all ORM layers probably assume mutable domain classes, all would would be under scrutiny.
So your question is: for object-relational mapping layers, how does functional programming work?
7eeb06460904081641u5ad5023dx6156e7b0a3919565 [at] mail [dot] gmail [dot] com" type="cite"> It isn't even involved. Abstract around the SQL queries, rather than around mutable objects that abstract around SQL queries, if you want to involve functional programming.Ok, some implications here. First off, Hibernate, and probably any other ORM layer is out the window solely because their architecture is all about magic abstractions around the domain classes (and the ability to mutate their values). If my direction is wrong here then all that follows is also, but I think you passively called out the architecture employed, so onward.
So we need a functional ORM; an evolved tool designed around a more functional paradigm. Two things jump out at me here, both rooted in the issue of immutability. First, Hibernate (and probably all decent ORM layers) employ at least one caching layer. If you load an entity by id, check cache first. If this theoretical functional ORM existed, how could it manage a cache? I don't know exactly how Hibernate implements it, but there's probably a Map<K, V> of id types to entity instances. That map is mutable, because cache changes over time (new entities, updates, and evictions). What would a functional cache map look like? Would it buck immutability here, or would it copy the entire cache to a new map each time a modification is made?
The other issue is one I raised in my last message: entity modification by derivation (client code points to new, modified instances, instead of the same, modified ones). I raised concerns on this that seemed to be validated by the responses, which basically confirm that, at present, Scala lacks a clean mechanism to do this.
Please excuse me if I misunderstood you and went down the wrong path. I think I'm on to what you're saying, but I'd very much appreciate expansion and further discussion on this topic. I'm a willing, sponge-minded student of Scala and FP, but certain areas seem gray at the moment. On the other hand, I quite like Scala's hybrid approach (OOP + FP), and ORM is a good accomplishment on the OOP front. I just want to closely observe how the paradigm meld can step it up a notch.
Thanks
-chris
7eeb06460904081641u5ad5023dx6156e7b0a3919565 [at] mail [dot] gmail [dot] com" type="cite">
2009/4/8 Chris Lewis <chris [at] thegodcode [dot] net" rel="nofollow">chris@thegodcode.net>
Nils Kilden-Pedersen wrote:On Wed, Apr 8, 2009 at 2:06 PM, Chris Lewis <chris [at] thegodcode [dot] net" target="_blank" rel="nofollow">chris@thegodcode.net> wrote:Yeah, and it's easy to imagine scenarios with simpler things like java.lang.String. But for ORM layers, like hibernate, how would it work? It's a given that data in a database must change - at least in certain applications (like my user prefs example). So there are several concerns here with immutability. First, and overly simplified entity class:
Does it make sense for entity classes to be immutable?
Ask it the other way around. Does it make sense for them to be mutable?
Having them be immutable, caching becomes infinitely easier and safer.
class User(val id: Long, val firstName: String, val lastName: String, val emailAddress: String)
Now assuming that an entity w/ idi 1 exists in the database, and that hibernate has been configured, AND we have a Session available as session, we can load the instance:
val u = session.load("User", 1)
Problem 1: Hibernate instantiates entities using a no-arg constructor, and then sets properties either via field or setter access. That's a "problem" of hibernate, but I'm curious how Scala users would deal with it.
Next up, changing the persistent data of that instance. Since User is immutable (val members only), we obviously can't say u.frstName = "Bill". So, we need some factory methods to do some derivation instantiation.
object User {
def modFirstName(u: User, firstName: String) = new User(u.id, firstName, u.lastName, u.emailAddress)
}
val u1 = User.modFirstName(u, "Bill")
Problem 2: I need to reference this new instance, but because I'm going full-on immutable, I can't (and I get this error on the REPL: <console>:9: error: recursive value u needs type val u = User.modFirstName(u, "Bill"))
Problem 3: Pretending problem 2 didn't exist, I've got a maintenance nightmare. If modifications mean new instances, then for every possible modification, or combination of modifications, I need a factory derivation method - or do some sketchy reflection. Yikes! I hope I'm missing something here...
Problem 4: Again ignoring problems 2 and 3, and assuming I've got the modification-by-derivation under control, the ORM knows about the original one; the one load()ed from the database. So how can this be dealt with? In hibernate I could do session.evict(u), and then /probably/ use session.update(u1) or maybe session.persist(u1) (needs testing), but I'm not sure about other ORMs.
Thanks tons for your input, and I'm sorry to bombard you with questions. As I said, I'm learning to think immutably, but for things like domain entity management I'm hitting some conceptual walls.
-chris
-- http://iamchrislewis.tumblr.com/
Fri, 2009-04-10, 19:07
#7
Re: functional newbie, domain entities
See LINQ to SQL for functional abstraction around SQL queries. I'd love to answer in more depth, but as I've never had to use databases I've largely avoided them, apart from some experiments with making SQL queries type-safe, so any further answers would be guesses.
I'd probably look at whatever Haskell does; as a general rule that's a good starting point.
2009/4/9 Daniel Wellman <etldan@gmail.com>
I'd probably look at whatever Haskell does; as a general rule that's a good starting point.
2009/4/9 Daniel Wellman <etldan@gmail.com>
Ricky Clarkson wrote:
>
> "But for ORM layers, like hibernate"
> So your question is: for object-relational mapping layers, how does
> functional programming work? It isn't even involved. Abstract around the
> SQL queries, rather than around mutable objects that abstract around SQL
> queries, if you want to involve functional programming.
>
Ricky,
You've made an interesting point - what would help me is some elaboration
about what abstracting around SQL queries means, or perhaps an example?
Thanks - and thanks Chris for asking an interesting question!
Cheers,
Dan
--
View this message in context: http://www.nabble.com/functional-newbie%2C-domain-entities-tp22957479p22962801.html
Sent from the Scala - User mailing list archive at Nabble.com.
Wed, 2009-04-15, 15:47
#8
RE: functional newbie, domain entities
Hi Chris,
> A little more specific; how does the mantra of object
> immutability mesh with ORM implementations?
[...]
> Does it make sense for entity classes to be immutable?
I had exactly the same questions some time ago when
I started to look into Scala.
All this FP and Immutability stuff confused me and I
reckon that will happen every time when atypical J2EE
developer will come to look into Scala and bump into
the common blog posts/tutorials/articles.
What happens to an object net where a Customer HasA
Bill which HasMany Positions which each HasAn Article
whose name has to be edited? Reincarnate the whole world?
The answers did not really convince me, until I reached
the meta conclusion that this is exactly why Scala *is* a
hybrid object-functional language: Allowing to model this
enterprise stuff in an adequate way.
Somewhere there are always variables which get updated.
What we have done in Java all these years is not suddenly
absolutely wrong! Point.
My result is: Use immutability and side-effect free programming
as often as possible (even in Java!) and where it is easily applicable
-we both will detect more and more places for it with more and more
experience- and you will enjoy the Scala language.
Otherwise you will simply end with headaches and some big frust.
(Trying to re-understand a complete EE application in FP ways
from now to tomorrow can left you with a feeling of stupidity
and so one has to recall explicitly being an experienced
developer which has done a job at least good enough for your
employer over all these last years).
Guys, this thing has to be addressed somewhere in literature
if you want to gain the mass of enterprise developers!
Ricky Clarkson wrote:
> [...] but as I've never had to use databases I've largely avoided
> them, apart from some experiments with making SQL queries type-safe,
Sorry Ricky, but this answer simply doesn't help us J2EE'lers,
which think in terms of tons of DB records and deep object nets.
> I'd probably look at whatever Haskell does; as a general rule
> that's a good starting point.
I think there's a reason why Haskell has not become the preferred tool
for the overall enterprise stuff ... perhaps wrong application domain?
Just my Cent(2)
Det
Wed, 2009-04-15, 16:37
#9
Re: functional newbie, domain entities
A few remarks from a long-time reader (from at least the days of John Harrop),
I agree with Dirk, where is the literature? Is there a missing chapter
34 in "Programming Scala": How to port a tangled ball of mutable state
Wed, 2009-04-15, 18:27
#10
Re: functional newbie, domain entities
2 quick additions on this topic.
1) To quote David Pollak in a message posted to this list on 4/8: "I spent 3 months puzzling with Lift's persistence classes and with writing immutable-style apps in Lift and came to the conclusion that the RDBMS represents state and trying to mix immutability and the RDBMS in a web app creates an untenable syntactic mess in Scala. Perhaps in another language, it might be possible, but in Scala, use JPA and getters/setter and understand that you do have mutability, but that the mutability is by and large isolated in the persistence-related classes."
I still flirt with how this could be different, but I just can't see any way around having to duplicate a full object graph, which is crazy. Clojure, a purer functional language than Scala, uses the notion of a transaction to change the value (immutable state) referred to by a Ref, which seems to be a mutable pointer (mutable in that its target value can be changed, but only within a transaction). If I'm not mistaken, this is STM (shared transactional memory) and was recently written about by Jonas Boner.
2) On the idea of UI components; I was recently thinking about the same thing. If you think about a windowing toolkit, say Swing for the heck of it, how could something like a JFrame fade in/out be accomplished? The fade effect would be the modification (ie, mutation) of the JFrame's opacity over a short time span. How can this be immutable? For each lapse in the interval, derive a new JFrame with the reduced opacity? It just doesn't seem to make sense. Of course, that could be my 2 core, sequentially bound mind. With 2000 cores, it may actually be more efficient.
Bradley Buchsbaum wrote:
1) To quote David Pollak in a message posted to this list on 4/8: "I spent 3 months puzzling with Lift's persistence classes and with writing immutable-style apps in Lift and came to the conclusion that the RDBMS represents state and trying to mix immutability and the RDBMS in a web app creates an untenable syntactic mess in Scala. Perhaps in another language, it might be possible, but in Scala, use JPA and getters/setter and understand that you do have mutability, but that the mutability is by and large isolated in the persistence-related classes."
I still flirt with how this could be different, but I just can't see any way around having to duplicate a full object graph, which is crazy. Clojure, a purer functional language than Scala, uses the notion of a transaction to change the value (immutable state) referred to by a Ref, which seems to be a mutable pointer (mutable in that its target value can be changed, but only within a transaction). If I'm not mistaken, this is STM (shared transactional memory) and was recently written about by Jonas Boner.
2) On the idea of UI components; I was recently thinking about the same thing. If you think about a windowing toolkit, say Swing for the heck of it, how could something like a JFrame fade in/out be accomplished? The fade effect would be the modification (ie, mutation) of the JFrame's opacity over a short time span. How can this be immutable? For each lapse in the interval, derive a new JFrame with the reduced opacity? It just doesn't seem to make sense. Of course, that could be my 2 core, sequentially bound mind. With 2000 cores, it may actually be more efficient.
Bradley Buchsbaum wrote:
43ec92880904150832t470f1b00r463b682b323a8f67 [at] mail [dot] gmail [dot] com" type="cite">A few remarks from a long-time reader (from at least the days of John Harrop), I agree with Dirk, where is the literature? Is there a missing chapter 34 in "Programming Scala": How to port a tangled ball of mutable state
Wed, 2009-04-15, 18:47
#11
Re: functional newbie, domain entities
Quoting Chris Lewis :
> (...) how could something like a JFrame fade in/out be accomplished?
> The fade effect would be the modification (ie, mutation) of the
> JFrame's opacity over a short time span. How can this be immutable?
> For each lapse in the interval, derive a new JFrame with the reduced
> opacity? It just doesn't seem to make sense. Of course, that could
> be my 2 core, sequentially bound mind. With 2000 cores, it may
> actually be more efficient.
Actually it's just with that part of the mind that says "when in my
programming language I instantiate a new object, also in the actual
runtime a new object will be instantiated, using new memory" etc. etc.
etc.
As you cannot assign something to the frame you can figure out how
many different ones you'll need with incompatible values at compile
time and generate a mutated-over-time single object or few-objects
pool to actually mirror what you write in your programming language.
Now whether scala does that or not, I don't know. But the general idea
of "I write this, so 1:1 it happens" seems quite persistent on here.
Why should it? if I map from 0 to 10, adding the values in a "new"
integer, obviously that can be unrolled, temporaries eliminated, etc.
etc. etc until it's a single accumulator aka result. Why do you think
the same can't be done for the frame ?
$0.42/20
Wed, 2009-04-15, 19:07
#12
Re: functional newbie, domain entities
Martin, I openly confess my struggle to think more functionally, hence
my repeated, direct confessions. The JFrame example isn't a matter of
"can" or "cannot," as I stated, but rather how can it be done
efficiently and sensibly with an arbitrary complex object (ie, one that
is a part of/depends on a large graph).
An integer, fine. A JFrame with no components, and therefore no
listeners, fine. But a JFrame rendering components to edit part of a
graph (like an Aritcle by a user, some user details, etc)? This pool of
precalculated frames of JFrames is now much more complicated, because
those immutable state representations will depend on a graph that
changes throughout execution. I understand it can be done, but it would
seem both inefficient and extremely cumbersome.
Like I said, perhaps the issue of efficiency will be addressed by the
coming concurrent (r)evolution. But the pain of deriving new objects
from previous ones for the sake of immutable objects (something I've
been referring to as "derivation instantiation") seems to bear
addressing at the syntax level. Otherwise I see no way of accomplishing
this generically without the use of some dirty property inspection via
reflection. As an ad-hoc example, consider:
class User(val name: String) {
def setName(name: String) = new User(name)
}
scala> val u1 = new User("Chris")
u1: User = User@c3b22c
scala> val u2 = u1.setName("Martin")
u2: User = User@9b12fb
The "setter" knows to return a new instance, leaving the original
unchanged. But having the burden of this on every single class is huge!
And then, what about the countless cases where you need to change > 1
property?
Thanks tons for keeping the discussion going list, really :-)
Martin S. Weber wrote:
> Quoting Chris Lewis :
>
>> (...) how could something like a JFrame fade in/out be accomplished?
>> The fade effect would be the modification (ie, mutation) of the
>> JFrame's opacity over a short time span. How can this be immutable?
>> For each lapse in the interval, derive a new JFrame with the reduced
>> opacity? It just doesn't seem to make sense. Of course, that could be
>> my 2 core, sequentially bound mind. With 2000 cores, it may actually
>> be more efficient.
>
> Actually it's just with that part of the mind that says "when in my
> programming language I instantiate a new object, also in the actual
> runtime a new object will be instantiated, using new memory" etc. etc.
> etc.
>
> As you cannot assign something to the frame you can figure out how
> many different ones you'll need with incompatible values at compile
> time and generate a mutated-over-time single object or few-objects
> pool to actually mirror what you write in your programming language.
> Now whether scala does that or not, I don't know. But the general idea
> of "I write this, so 1:1 it happens" seems quite persistent on here.
> Why should it? if I map from 0 to 10, adding the values in a "new"
> integer, obviously that can be unrolled, temporaries eliminated, etc.
> etc. etc until it's a single accumulator aka result. Why do you think
> the same can't be done for the frame ?
>
> $0.42/20
>
Wed, 2009-04-15, 19:17
#13
Re: functional newbie, domain entities
Chris Lewis wrote:
> An integer, fine. A JFrame with no components, and therefore no
> listeners, fine. But a JFrame rendering components to edit part of a
> graph (like an Aritcle by a user, some user details, etc)? This pool of
> precalculated frames of JFrames is now much more complicated, because
> those immutable state representations will depend on a graph that
> changes throughout execution. I understand it can be done, but it would
> seem both inefficient and extremely cumbersome.
>
What's inefficient/cumbersome about assigning a new object, most of which is the same but whose new
value is a new value? Is it a conceptual inefficiency/encumbrance you're seeing, or something
unique to the Scala language or its current implementation?
~~ Robert Fischer.
Grails Training http://GroovyMag.com/training
Smokejumper Consulting http://SmokejumperIT.com
Enfranchised Mind Blog http://EnfranchisedMind.com/blog
Check out my book, "Grails Persistence with GORM and GSQL"!
http://www.smokejumperit.com/redirect.html
Wed, 2009-04-15, 19:27
#14
Re: functional newbie, domain entities
Brad, et al,
Out of curiousity, have you looked at monads? Have you looked, for example, at the state monad and the standard update-leaf-nodes-in-a-tree-example?
Monads are not as well supported in Scala, but it's not terrifically painful to port them over from Haskell. Tony Morris did an implementation in scalaz. Just doing a hand port of the state monad and example might provide some clues regarding how to address state in a functional setting, and why you might want to do things that way.
(A couple of years back i did a straight-up Java implementation of the state monad and standard example, just for grins, to see how painful it was. It was edifying.) You get a better feel for where the trade-offs are, likeissues regarding space consumption versus design flexibility, as well as insights into the kinds of optimizations that have to go on in ghc.
i submit that there is a reason why there is a cottage industry growing up around monads.
Best wishes,
--greg
On Wed, Apr 15, 2009 at 8:32 AM, Bradley Buchsbaum <brad.buchsbaum@gmail.com> wrote:
Out of curiousity, have you looked at monads? Have you looked, for example, at the state monad and the standard update-leaf-nodes-in-a-tree-example?
Monads are not as well supported in Scala, but it's not terrifically painful to port them over from Haskell. Tony Morris did an implementation in scalaz. Just doing a hand port of the state monad and example might provide some clues regarding how to address state in a functional setting, and why you might want to do things that way.
(A couple of years back i did a straight-up Java implementation of the state monad and standard example, just for grins, to see how painful it was. It was edifying.) You get a better feel for where the trade-offs are, likeissues regarding space consumption versus design flexibility, as well as insights into the kinds of optimizations that have to go on in ghc.
i submit that there is a reason why there is a cottage industry growing up around monads.
Best wishes,
--greg
On Wed, Apr 15, 2009 at 8:32 AM, Bradley Buchsbaum <brad.buchsbaum@gmail.com> wrote:
A few remarks from a long-time reader (from at least the days of John Harrop),
I agree with Dirk, where is the literature? Is there a missing chapter
34 in "Programming Scala": How to port a tangled ball of mutable state
Wed, 2009-04-15, 19:37
#15
Re: functional newbie, domain entities
> A JFrame with no components, and therefore no listeners,
> fine. But a JFrame rendering components to edit part of a graph (like an
> Aritcle by a user, some user details, etc)?
as an aside, it might be that one looks at an overall imperative
system and think about changing some subset to be more purely
functional, and then thinks "but how can it possibly work with the
overall imperative system?!" when one might better go whole-hog and
think "ok, so i guess i need to reconsider the fact that the whole
overall imperative system is holding me down!" (i'm not saying that
is explicitly the case here, it is just a general thought about
possible mental modes in considering fp vs. non-fp.)
sincerely.
Wed, 2009-04-15, 19:37
#16
Re: functional newbie, domain entities
Chris,
I don't think you should try and make everything immutable just for the sake of branding the code as "functional". Not everything can become immutable, at least not without going very, very slow compared to mutable data structures. In particular, for any reference cycles that exist in a structure, the whole cycle (at least) must be copied for any update in a functional way. And guess what, a typical swing gui has way more cycles than this list's members have fingers to count them, so you would end up coping the entire gui everytime the user clicked on a check box, or even merely pressed the tab key to move the focus elsewhere. And if you think more processors could make the problem somehow disappear, are you sure you would be happy buying all those processors just to repeatedly copy all the gui? (And after performing the copy, probably throwing away the old versions). Surely there *must* be more important computations to be performed than that.
In database-mapped object graphs perhaps there would be less copying to do and immutability perhaps viable, assumming that such object graphs would be small and without many cycles. But in those cases, such objects are typically short-lived (transaction-scoped) and used only by a single thread, so immutability doesn't buy that much anyway.
Dimitris
2009/4/15 Chris Lewis <chris@thegodcode.net>
I don't think you should try and make everything immutable just for the sake of branding the code as "functional". Not everything can become immutable, at least not without going very, very slow compared to mutable data structures. In particular, for any reference cycles that exist in a structure, the whole cycle (at least) must be copied for any update in a functional way. And guess what, a typical swing gui has way more cycles than this list's members have fingers to count them, so you would end up coping the entire gui everytime the user clicked on a check box, or even merely pressed the tab key to move the focus elsewhere. And if you think more processors could make the problem somehow disappear, are you sure you would be happy buying all those processors just to repeatedly copy all the gui? (And after performing the copy, probably throwing away the old versions). Surely there *must* be more important computations to be performed than that.
In database-mapped object graphs perhaps there would be less copying to do and immutability perhaps viable, assumming that such object graphs would be small and without many cycles. But in those cases, such objects are typically short-lived (transaction-scoped) and used only by a single thread, so immutability doesn't buy that much anyway.
Dimitris
2009/4/15 Chris Lewis <chris@thegodcode.net>
Martin, I openly confess my struggle to think more functionally, hence my repeated, direct confessions. The JFrame example isn't a matter of "can" or "cannot," as I stated, but rather how can it be done efficiently and sensibly with an arbitrary complex object (ie, one that is a part of/depends on a large graph).
An integer, fine. A JFrame with no components, and therefore no listeners, fine. But a JFrame rendering components to edit part of a graph (like an Aritcle by a user, some user details, etc)? This pool of precalculated frames of JFrames is now much more complicated, because those immutable state representations will depend on a graph that changes throughout execution. I understand it can be done, but it would seem both inefficient and extremely cumbersome.
Like I said, perhaps the issue of efficiency will be addressed by the coming concurrent (r)evolution. But the pain of deriving new objects from previous ones for the sake of immutable objects (something I've been referring to as "derivation instantiation") seems to bear addressing at the syntax level. Otherwise I see no way of accomplishing this generically without the use of some dirty property inspection via reflection. As an ad-hoc example, consider:
class User(val name: String) {
def setName(name: String) = new User(name)
}
scala> val u1 = new User("Chris")
u1: User = User@c3b22c
scala> val u2 = u1.setName("Martin")
u2: User = User@9b12fb
The "setter" knows to return a new instance, leaving the original unchanged. But having the burden of this on every single class is huge! And then, what about the countless cases where you need to change > 1 property?
Thanks tons for keeping the discussion going list, really :-)
Martin S. Weber wrote:
Quoting Chris Lewis <chris@thegodcode.net>:
(...) how could something like a JFrame fade in/out be accomplished? The fade effect would be the modification (ie, mutation) of the JFrame's opacity over a short time span. How can this be immutable? For each lapse in the interval, derive a new JFrame with the reduced opacity? It just doesn't seem to make sense. Of course, that could be my 2 core, sequentially bound mind. With 2000 cores, it may actually be more efficient.
Actually it's just with that part of the mind that says "when in my programming language I instantiate a new object, also in the actual runtime a new object will be instantiated, using new memory" etc. etc. etc.
As you cannot assign something to the frame you can figure out how many different ones you'll need with incompatible values at compile time and generate a mutated-over-time single object or few-objects pool to actually mirror what you write in your programming language. Now whether scala does that or not, I don't know. But the general idea of "I write this, so 1:1 it happens" seems quite persistent on here. Why should it? if I map from 0 to 10, adding the values in a "new" integer, obviously that can be unrolled, temporaries eliminated, etc. etc. etc until it's a single accumulator aka result. Why do you think the same can't be done for the frame ?
$0.42/20
Wed, 2009-04-15, 19:47
#17
Re: functional newbie, domain entities
Quoting Chris Lewis :
> Martin, I openly confess my struggle to think more functionally,
> hence my repeated, direct confessions. The JFrame example isn't a
> matter of "can" or "cannot," as I stated, but rather how can it be
> done efficiently and sensibly with an arbitrary complex object (ie,
> one that is a part of/depends on a large graph).
=> In your language, think functional. In the
implementation/compilation, act imperative. Hide imperativeness from
language point of view. In the language just get amazed by how fast
you can copy whole instance trees with mutating a few values :-)
> An integer, fine. A JFrame with no components, and therefore no
> listeners, fine. But a JFrame rendering components to edit part of a
> graph (like an Aritcle by a user, some user details, etc)? This pool
> of precalculated frames of JFrames is now much more complicated,
> because those immutable state representations will depend on a graph
> that changes throughout execution.
...and thus also could be represented by exact copies of the full tree
of things with just a few bits and pieces changed...
> I understand it can be done, but it would seem both inefficient and
> extremely cumbersome.
It all depends on how it's represented to you, doesn't it? If the
syntax for "copy all this but mutate that" was trivial, even as easy
as a setter (e.g. going => this.type and not => Unit) how much of it
would you actually notice?
>
> Like I said, perhaps the issue of efficiency will be addressed by
> the coming concurrent (r)evolution. But the pain of deriving new
> objects from previous ones for the sake of immutable objects
> (something I've been referring to as "derivation instantiation")
> seems to bear addressing at the syntax level.
"And" I always liked "<-"
"Or" as an updated interpretation of the current syntax.
> Otherwise I see no way of accomplishing this generically without the
> use of some dirty property inspection via reflection. As an ad-hoc
> example, consider:
>
> class User(val name: String) {
> def setName(name: String) = new User(name)
> }
>
> scala> val u1 = new User("Chris")
> u1: User = User@c3b22c
>
> scala> val u2 = u1.setName("Martin")
> u2: User = User@9b12fb
maybe this is going to change with the ability in 2.8 (?) to perform a
"copy with mutation" of an existing object. What I'm referring to is
the following (sticking to your example):
val martin = new User("whatever").setName("Martin")
Why would the first User object have to be a different instance than
the second, given you have no handle to it? I mean, *internally* this
could well compile to e.g., so to speak:
class User$(var name: String) { def setName = name_=_ andThen { x=> this } }
Yes I know we're not there. But just as you can think of any mutation
as construction of a new value, altering the parts you want to assign
to in the receiving object's constructor, you can as well think of any
construction as a mutation of an existing object. Of course the hard
part is analyzing if there's handles to the previous state of object,
do they stay around etc.
In the object graph example though iiuc there's no two reference onto
the before-change and after-change object tree. So even a full
deep-copy-and-change-one-instance-property could just compile to
mutate-property-in-place-and-return-this and thus to, set one variable
in the runtime.
As I stated, just of the top of my head, probably (quite unsupported
by the current state of scala, vapor'd thoughts etc. Writing it still
because I believe we'll get there, with scala or not, someday). You
have to keep in mind that in FP you mutate data a lot... actually by
its construction imo fp attempts to force you in mutating/computing
data just -once- and thus you don't need variables...but in the end
just one single function whose direct or indirect arguments contain
all the computation you need/want....
>
> The "setter" knows to return a new instance, leaving the original
> unchanged. But having the burden of this on every single class is
> huge! And then, what about the countless cases where you need to
> change > 1 property?
Actually what I don't understand is why scala's setters are => Unit
and not => this.type ...
> Thanks tons for keeping the discussion going list, really :-)
Oh I like to embarass myself publically ;-)
-Martin
Wed, 2009-04-15, 19:47
#18
Re: functional newbie, domain entities
> And guess what, a typical swing gui has way more cycles than
> this list's members have fingers to count them
ja, if the overall system does things which are "bad" as far as pure
fp is concerned, it can be awful hard to carve out sub-parts to be
nicely pure fp. tho, in case anybody might, please don't assume pure
fp has clearly bad just because swing isn't pure fp :-)
sincerely.
Wed, 2009-04-15, 19:57
#19
Re: functional newbie, domain entities
Quoting Jim Andreou :
> (...)
> (And after performing the copy, probably throwing away the old versions).
> (...)
Obviously, if you can throw away the old version, the compiler(*) can
infer that it doesn't need a new version, and thus not perform a copy
at all.
(*) Not the current scala compiler, also obviously.
-Martin
Wed, 2009-04-15, 20:07
#20
Re: functional newbie, domain entities
Probably a future-proof, NP-complete problem.
2009/4/15 Martin S. Weber <martin.weber@nist.gov>
2009/4/15 Martin S. Weber <martin.weber@nist.gov>
Quoting Jim Andreou <jim.andreou@gmail.com>:
(...)
(And after performing the copy, probably throwing away the old versions).
(...)
Obviously, if you can throw away the old version, the compiler(*) can infer that it doesn't need a new version, and thus not perform a copy at all.
(*) Not the current scala compiler, also obviously.
-Martin
Wed, 2009-04-15, 20:37
#21
overheard at val's house
On Wed, Apr 15, 2009 at 11:32:24AM -0400, Bradley Buchsbaum wrote:
> We're supposed to be a little of ashamed of "var", but there he is
> looking all scrawny and pathetic. He's the no-good, slightly vicious,
> step-son who maybe should never have been born. "val" is the good son,
> captain of the soccer team, with a bright future, probably will go to
> an elite University and run for office some day.
"Mom, I'm home!"
"Oh hi V... oh, it's you. Hello Var."
"Nice to see you too, MOM."
"Don't you start that with me. We've given you chance after chance, but
you always promise one thing and end up delivering another. I'm about
ready to change the locks."
"How can you be so cold, mom? So I change my mind sometimes, so what?
Isn't that my prerogative? When the facts change, I change with them!"
"Your brother seems to get along fine without being such a
flibbertigibbet."
"Val, Val, Val! If I hear one more word about your little angel I swear
to god..."
"I can ask Val to do half a dozen things all at once, and I know they'll
all get done. With you it's anyone's guess WHAT will happen. Remember
when I asked you to mow the lawn and buy some milk, and instead you
burned down the neighbor's house?"
"But who do you come running to when you need something done fast, huh?
Oh you love to show off Val when company comes over, but most of the
time I'm the one really doing all the dirty work!"
"Some day, son, you're going to realize there's a right way and a wrong
way to do things. And until then we can't have you around here anymore."
"I... I can't believe this is happening. Where am I going to go?"
"That's your problem, but make sure Val knows where to find you, OK?"
"You're a monster!"
"That would hurt, if I didn't know you'd feel differently soon. You
always do."
etc. etc.
Wed, 2009-04-15, 21:07
#22
Re: overheard at val's house
> "Mom, I'm home!"
wow.
just, like: wow.
Thu, 2009-04-16, 00:57
#23
Re: functional newbie, domain entities
If the overall system is crap, it can be hard to carve out good bits. But worth doing. Functional bits are good bits, in most systems. Look at which bits of code contain the most bugs, in any medium sized project. They'll be the ones with hard-to-understand state changes, the 'dysfunctional' bits.
If the overall system does stuff that doesn't appear to fit into FP, you will probably find you can decompose it into layers. Some pure code gets called by some impure code, and that impure code gets used but without exposing the impurity, producing another pure layer.
For example, Random.nextInt is impure, because there's a seed that gets modified. One might construct some form of stream (but not scala.Stream, ugh) containing the values returned from Random.nextInt. The stream is then pure, even if it is implemented in terms of impure code.
And if you're lucky, two pure bits with an impure bit in the middle can eventually become one bigger pure bit.
2009/4/15 Raoul Duke <raould@gmail.com>
2009/4/15 Raoul Duke <raould@gmail.com>
> And guess what, a typical swing gui has way more cycles than
> this list's members have fingers to count them
ja, if the overall system does things which are "bad" as far as pure
fp is concerned, it can be awful hard to carve out sub-parts to be
nicely pure fp. tho, in case anybody might, please don't assume pure
fp has clearly bad just because swing isn't pure fp :-)
sincerely.
Thu, 2009-04-16, 13:37
#24
RE: functional newbie, domain entities
Martin, (and Raoul too)
(Martin S. Weber wrote):
> Obviously, if you can throw away the old version, the
> compiler(*) can
> infer that it doesn't need a new version, and thus not
> perform a copy
> at all.
>
> (*) Not the current scala compiler, also obviously.
>
> -Martin
How can the compiler do that?
The possibility to throw away (i.e.: no references) is
detected by the garbage collector at runtime, I think?
Beside, what I cannot see here is:
You have an object. You call a setter on this object,
and for the sake of pure FP this setter creates a new
instance i.e. modified copy. The syntax of the setter
is generally kept like before, so you do not notice it
as a user:
myobject.setValue(newvalue) // now returns modified version
// instead of nothing.
Now you say, the compiler can optimise the unneccessary
new version creation away and instead reuse the old
version in modified form under the hood ....
So instead of (mutable)
instance.setValue(newval) <=> this.value := newval
we have now (optimised immutable)
instance.setValue(newval) <=> this.value := newval ; return this;
Aehm ... what have we gained now? We are as mutable
as we have been before. At least in the syntax (looks similar)
and and least in the runtime (copy optimised away, leaving us
with modification).
But we can brand the whole system now FP because .... why?
Because it *would* have copied if there *would* have been
references to the old object?
(Which perhaps I *would* have liked to point to the new version).
No, as far as I see this discussion is not about optimising,
runtime load or such stuff. It is about how to think about a
problem.
> From: Raoul Duke [mailto:raould@gmail.com]
> > And guess what, a typical swing gui has way more cycles than
> > this list's members have fingers to count them
>
> ja, if the overall system does things which are "bad" as far as pure
> fp is concerned, it can be awful hard to carve out sub-parts to be
> nicely pure fp. tho, in case anybody might, please don't assume pure
> fp has clearly bad just because swing isn't pure fp :-)
1.) I told about the headaches trying to rethink a typical EE
application in FP. If this is the precondition, we will have
a FP style EE in fifty years: When DB and Appserver and GUI framework
all have adapted functional style.
2.) So you are saying that Swing is not FP and that is the problem.
So instead of the ScalaSwing wrap there should better be written a
ScalaGUI framework.
BTW: Any example for a purely functional style GUI framework?
Or in better words:
I want to see a running app with a form where for example someone
manages an Audio-CD and Video-DVD collection, dynamically enabling
and disabling fields and buttons, setting selections on tables,
changing options in comboboxes and selecting values from them,
all this typical GUI stuff (and possibly persistence stuff) for a
typical data maintenace application to be found in so many offices
today.
AND all of this written purely functional.
That would perhaps be a convincing showcase for developers like me
and all the others which ask the same questions.
I am really eager to learn such new things which -beside being
interesting- could help me in my job (and my bit of experiments
with Scala already changed my style) and bring me forward as a
developer, but all I/we got so far about this topic is:
"It is possible" - (How?)
"The platform is not functional enough" - (so what now?)
"I'm not doing such things either" (doesn't help ME)
"Look at monads" - (So where's a more than theoretical showcase)
My current impression so far is: pure FP as solution for all
problem domains is NOT the right answer. Some problems are in
origin functional or can easily be seen as such, some other
problems are in origin based on mutable objects or at least
this mindset fits easily.
Use the best tool for the respective domain otherwise you will
always twist someones brain by squeezing the problem into your
Prokrustes paradigm.
KR
Det
Thu, 2009-04-16, 14:27
#25
Re: functional newbie, domain entities
> myobject.setValue(newvalue)
Um, if that doesn't mutate anything, you'll have to read its return value for it to be useful. The syntax certainly doesn't look the same.
2009/4/16 Detering Dirk <Dirk.Detering@bitmarck.de>
Um, if that doesn't mutate anything, you'll have to read its return value for it to be useful. The syntax certainly doesn't look the same.
2009/4/16 Detering Dirk <Dirk.Detering@bitmarck.de>
Martin, (and Raoul too)
(Martin S. Weber wrote):
> Obviously, if you can throw away the old version, the
> compiler(*) can
> infer that it doesn't need a new version, and thus not
> perform a copy
> at all.
>
> (*) Not the current scala compiler, also obviously.
>
> -Martin
How can the compiler do that?
The possibility to throw away (i.e.: no references) is
detected by the garbage collector at runtime, I think?
Beside, what I cannot see here is:
You have an object. You call a setter on this object,
and for the sake of pure FP this setter creates a new
instance i.e. modified copy. The syntax of the setter
is generally kept like before, so you do not notice it
as a user:
myobject.setValue(newvalue) // now returns modified version
// instead of nothing.
Now you say, the compiler can optimise the unneccessary
new version creation away and instead reuse the old
version in modified form under the hood ....
So instead of (mutable)
instance.setValue(newval) <=> this.value := newval
we have now (optimised immutable)
instance.setValue(newval) <=> this.value := newval ; return this;
Aehm ... what have we gained now? We are as mutable
as we have been before. At least in the syntax (looks similar)
and and least in the runtime (copy optimised away, leaving us
with modification).
But we can brand the whole system now FP because .... why?
Because it *would* have copied if there *would* have been
references to the old object?
(Which perhaps I *would* have liked to point to the new version).
No, as far as I see this discussion is not about optimising,
runtime load or such stuff. It is about how to think about a
problem.
> From: Raoul Duke [mailto:raould@gmail.com]
> > And guess what, a typical swing gui has way more cycles than
> > this list's members have fingers to count them
>
> ja, if the overall system does things which are "bad" as far as pure
> fp is concerned, it can be awful hard to carve out sub-parts to be
> nicely pure fp. tho, in case anybody might, please don't assume pure
> fp has clearly bad just because swing isn't pure fp :-)
1.) I told about the headaches trying to rethink a typical EE
application in FP. If this is the precondition, we will have
a FP style EE in fifty years: When DB and Appserver and GUI framework
all have adapted functional style.
2.) So you are saying that Swing is not FP and that is the problem.
So instead of the ScalaSwing wrap there should better be written a
ScalaGUI framework.
BTW: Any example for a purely functional style GUI framework?
Or in better words:
I want to see a running app with a form where for example someone
manages an Audio-CD and Video-DVD collection, dynamically enabling
and disabling fields and buttons, setting selections on tables,
changing options in comboboxes and selecting values from them,
all this typical GUI stuff (and possibly persistence stuff) for a
typical data maintenace application to be found in so many offices
today.
AND all of this written purely functional.
That would perhaps be a convincing showcase for developers like me
and all the others which ask the same questions.
I am really eager to learn such new things which -beside being
interesting- could help me in my job (and my bit of experiments
with Scala already changed my style) and bring me forward as a
developer, but all I/we got so far about this topic is:
"It is possible" - (How?)
"The platform is not functional enough" - (so what now?)
"I'm not doing such things either" (doesn't help ME)
"Look at monads" - (So where's a more than theoretical showcase)
My current impression so far is: pure FP as solution for all
problem domains is NOT the right answer. Some problems are in
origin functional or can easily be seen as such, some other
problems are in origin based on mutable objects or at least
this mindset fits easily.
Use the best tool for the respective domain otherwise you will
always twist someones brain by squeezing the problem into your
Prokrustes paradigm.
KR
Det
Thu, 2009-04-16, 14:37
#26
Re: overheard at val's house
I knew it would happen. Too much compiler source code sent him mad. He'll be playing poker for a living, next thing you know.
2009/4/15 Paul Phillips <paulp@improving.org>
2009/4/15 Paul Phillips <paulp@improving.org>
On Wed, Apr 15, 2009 at 11:32:24AM -0400, Bradley Buchsbaum wrote:
> We're supposed to be a little of ashamed of "var", but there he is
> looking all scrawny and pathetic. He's the no-good, slightly vicious,
> step-son who maybe should never have been born. "val" is the good son,
> captain of the soccer team, with a bright future, probably will go to
> an elite University and run for office some day.
"Mom, I'm home!"
"Oh hi V... oh, it's you. Hello Var."
"Nice to see you too, MOM."
"Don't you start that with me. We've given you chance after chance, but
you always promise one thing and end up delivering another. I'm about
ready to change the locks."
"How can you be so cold, mom? So I change my mind sometimes, so what?
Isn't that my prerogative? When the facts change, I change with them!"
"Your brother seems to get along fine without being such a
flibbertigibbet."
"Val, Val, Val! If I hear one more word about your little angel I swear
to god..."
"I can ask Val to do half a dozen things all at once, and I know they'll
all get done. With you it's anyone's guess WHAT will happen. Remember
when I asked you to mow the lawn and buy some milk, and instead you
burned down the neighbor's house?"
"But who do you come running to when you need something done fast, huh?
Oh you love to show off Val when company comes over, but most of the
time I'm the one really doing all the dirty work!"
"Some day, son, you're going to realize there's a right way and a wrong
way to do things. And until then we can't have you around here anymore."
"I... I can't believe this is happening. Where am I going to go?"
"That's your problem, but make sure Val knows where to find you, OK?"
"You're a monster!"
"That would hurt, if I didn't know you'd feel differently soon. You
always do."
etc. etc.
--
Paul Phillips | Giving every man a vote has no more made men wise
Vivid | and free than Christianity has made them good.
Empiricist | -- H. L. Mencken
pal, i pill push |----------* http://www.improving.org/paulp/ *----------
Thu, 2009-04-16, 14:57
#27
RE: functional newbie, domain entities
> > myobject.setValue(newvalue)
>
> Um, if that doesn't mutate anything, you'll have to read its
> return value for it to be useful. The syntax certainly
> doesn't look the same.
Right ;-) . "The same" was indeed only true for the
possible right side part of an assignment, which I left
away intentionally.
So instead of
myobject.setValue(newvalue)
I would have
myobject = myobject.setValue(newvalue)
what would left the object referenced by myobject being immutable,
but the part of the code where I am in (say: where the ref 'myobject'
is declared) would be mutable, and so the object where this code
possibly
resides) => var myobject .
To avoid that, I would have to write:
val mynewobject = myobject.setValue(newvalue)
Or I would have to copy the current object (this) itsself,
with myobject now pointing to the modified copy.
But that could only be done from outside
As this proposal here states, the implementation would result in:
http://docs.google.com/Doc?id=dc42h45k_42dpmj57fg
val tempChild = rob.child setFavourite(true)
val bob = rob setName "Bob" setWeight 113 setChild tempChild
For a deep net this would mean to create a good bunch of
temp vals and code which would in my taste know too much
about the underlying structure, necessarily to modify it,
and would involve creation of a new val (here bob, replacing rob)
on top level of this chain either, or you would escalate the
problem further up until you reach the main method.
So for example with:
val top = formertop.parent.child.grandchild.setValue(newval)
Thu, 2009-04-16, 15:07
#28
Re: functional newbie, domain entities
> I am really eager to learn such new things which -beside being
> interesting- could help me in my job (and my bit of experiments
> with Scala already changed my style) and bring me forward as a
> developer, but all I/we got so far about this topic is:
> "It is possible" - (How?)
> "The platform is not functional enough" - (so what now?)
> "I'm not doing such things either" (doesn't help ME)
> "Look at monads" - (So where's a more than theoretical showcase)
There was a similar discussion on the comments over at
http://araujoluis.blogspot.com/2007/04/haskell-gui-programing.html
(Haskell, GUI, monads) - is monads the way to go in Scala?
Francisco
Thu, 2009-04-16, 15:27
#29
Re: functional newbie, domain entities
On Thu, Apr 16, 2009 at 2:57 PM, francisco treacy
wrote:
>> I am really eager to learn such new things which -beside being
>> interesting- could help me in my job (and my bit of experiments
>> with Scala already changed my style) and bring me forward as a
>> developer, but all I/we got so far about this topic is:
>> "It is possible" - (How?)
>> "The platform is not functional enough" - (so what now?)
>> "I'm not doing such things either" (doesn't help ME)
>> "Look at monads" - (So where's a more than theoretical showcase)
>
> There was a similar discussion on the comments over at
> http://araujoluis.blogspot.com/2007/04/haskell-gui-programing.html
> (Haskell, GUI, monads) - is monads the way to go in Scala?
Monads are certainly *a* way to go. I prefer functional reactive
programming (FRP). I would look at FrTime (PLT Scheme) and Flapjax
(Javascript) for a functional reactive DSL embedded in a call-by-value
mostly functional language. This approach is asynchronous, which is an
advantage over the Haskell FRP implementations and, at least for
Flapjax, has been used in some real systems.
N.
Thu, 2009-04-16, 15:37
#30
Re: overheard at val's house
On Thu, Apr 16, 2009 at 3:25 PM, Ricky Clarkson <ricky.clarkson@gmail.com> wrote:
I knew it would happen. Too much compiler source code sent him mad. He'll be playing poker for a living, next thing you know.
I knew I was in danger, made $100 yesterday (Hand: A7 , Flop: 777)
2009/4/15 Paul Phillips <paulp@improving.org>
On Wed, Apr 15, 2009 at 11:32:24AM -0400, Bradley Buchsbaum wrote:
> We're supposed to be a little of ashamed of "var", but there he is
> looking all scrawny and pathetic. He's the no-good, slightly vicious,
> step-son who maybe should never have been born. "val" is the good son,
> captain of the soccer team, with a bright future, probably will go to
> an elite University and run for office some day.
"Mom, I'm home!"
"Oh hi V... oh, it's you. Hello Var."
"Nice to see you too, MOM."
"Don't you start that with me. We've given you chance after chance, but
you always promise one thing and end up delivering another. I'm about
ready to change the locks."
"How can you be so cold, mom? So I change my mind sometimes, so what?
Isn't that my prerogative? When the facts change, I change with them!"
"Your brother seems to get along fine without being such a
flibbertigibbet."
"Val, Val, Val! If I hear one more word about your little angel I swear
to god..."
"I can ask Val to do half a dozen things all at once, and I know they'll
all get done. With you it's anyone's guess WHAT will happen. Remember
when I asked you to mow the lawn and buy some milk, and instead you
burned down the neighbor's house?"
"But who do you come running to when you need something done fast, huh?
Oh you love to show off Val when company comes over, but most of the
time I'm the one really doing all the dirty work!"
"Some day, son, you're going to realize there's a right way and a wrong
way to do things. And until then we can't have you around here anymore."
"I... I can't believe this is happening. Where am I going to go?"
"That's your problem, but make sure Val knows where to find you, OK?"
"You're a monster!"
"That would hurt, if I didn't know you'd feel differently soon. You
always do."
etc. etc.
--
Paul Phillips | Giving every man a vote has no more made men wise
Vivid | and free than Christianity has made them good.
Empiricist | -- H. L. Mencken
pal, i pill push |----------* http://www.improving.org/paulp/ *----------
--
Viktor Klang
Senior Systems Analyst
Thu, 2009-04-16, 15:47
#31
RE: functional newbie, domain entities
Quoting Detering Dirk :
> Martin, (and Raoul too)
>
> (Martin S. Weber wrote):
>> Obviously, if you can throw away the old version, the
>> compiler(*) can
>> infer that it doesn't need a new version, and thus not
>> perform a copy
>> at all.
>>
>> (*) Not the current scala compiler, also obviously.
>>
>> -Martin
>
> How can the compiler do that?
> The possibility to throw away (i.e.: no references) is
> detected by the garbage collector at runtime, I think?
Well, if you have
var a = new Something // 1
a = new Something //2
then it's obvious the compiler can know at line 2 that there will be
no way for you to refer to the Something from line 1 and thus not
allocate a new instance. Actually for any var that references
something (and that is solely referenced from there) the compiler
could know that you're no longer interested in the "past", after all
you did reassign to the value. In cases like this, and with the above
stated, "obvious" suggestion, a "setter" returning a new instance with
a modified member, and a var are idempotent. So you could replace any
var by new X { modify } and eliminate previous versions of the val.
This does "suck" the modification "into" the method/function call
parameters naturally, (as you cannot reassign to a val). Alternatively
you could replace any method parameter that is a modified instance by
a series of var x = init, x = modification, method(x). So in the end,
the programming language could present you with a purely functional
view of the world while, obviously given also the way these-days cpus
work, somewhen it's gonna be an imperative program that's being
executed.
I'm not saying that this works right now or something. It keeps coming
up though, that functional style means run-time overhead, duplicating
things etc. etc.. People claimed that lambda calls/recursive functions
cannot be equal in run-time to an imperative goto for quite some time,
too, until some "Guy" named "Steele" wrote a paper "Debunkning the
'expensive procedure call' myth, or, procedure call implementations
considered harmful, or, lambda: the ultimate goto". That was over 30
years ago and it still hasn't trickled down into the heads of people,
that there is a broad range of recursive function use-cases that
indeed *are* equivalent to goto-loops (aka while).
Just as the statement, recursive functions must be more costly than
whiles is generally wrong, I claim that indeed the statement,
immutable data has to result in more runtime overhead than mutable
data, is as wrong. I haven't done any research on the subject, but
it's obvious that in some cases you could (as a human) well see how a
var and a val could indeed be compiled to equivalent, if not identical
code. Actually I had hoped that some scala users, given the
environment, did do some research on the subject and could either
correct me or agree with me, also providing some more insightful
papers etc. etc. ISTM the scala-user population is more imperative
than functional tho (no pun intended). I'll rest my case and maybe
will reopen it if I had (or ever will have) the chance to do some
actual research on the subject. So feel free to claim: FP results in
less efficient code than IP and feel well about it.
-Martin
Thu, 2009-04-16, 16:47
#32
RE: functional newbie, domain entities
Martin, thanks for your explanations, which I will
walk through thoroughly. Now only one thing:
> So feel free to claim: FP results in
> less efficient code than IP and feel well about it.
(perhaps I should have added that to my quote list
of non-helping comments).
If you will bother re-reading my very first post in
this thread regarding the "stupid feeling", the efficiency
of code per se is not my point.
It all is about understanding.
The thing is, that as a typical Java developer you
now get dumped with messages like "mutable code and
stateful code is bad" and "imperative is bad" and
"pure functional way makes the world better", but
trying to get the paradigm and (that is my point!)
applying that to the business developer's problem
space (my current job realm) seems almost impossible.
I have enough problems of testability and maintainability
that I am very well interested in taking all the claims
about the hail of FP for true, but -to be honest- there is so
much talk about it, and when asking deeper one gets only
tossed at with some abstract artifical snippets (the fibonacci
kind), with some theoretical stuff which looks very complex
to achieve what we Java people already do every day since years
(IO monads), and with many claims and with statements of
how bad all this current Java is.
This comes up again and again when someone asks like the
thread creator did.
So I must say that I am now fed up with so much talk and
articles and claims, as for any other language (at least
the ones claiming to be of practical use) someone will very
soon point you to some code examples on some *forge site,
but here I am missing the showcase for the claims.
I am creating a standalone but not too simple desktop app
in Scala (when time allows), but that is exactly why I stopped
trying to get all this FP stuff in and decided to do it
the known way: I was simply blocked to standstill when even
trying to create a more than simplest domain model with
immutable collections and without vars.
So now I can explore the Scala things and perhaps learn at
least some good new stuff for my job.
I can't find the pure FP design solution for my application on
my own, and tutoring for that and a showcase to study I have
not found and was never part of the answers here.
So I concluded that I was wrong assuming in the first place
that some pure FP style is "the Scala way" and 'var'/mutable
collections only compromise to the old Java people.
It's all like talking about elephants with no one taking you
at hand and leading you to the zoo.
I am willing to believe you that it works, but hearing about
does not replace seeing and touching yourself.
(PS: This grumbling is all regarding the pure FP-way, not Scala
and its features in principle, for which one can find more and more
good literature and public code examples!)
KR
Det
Sun, 2010-01-03, 08:12
#33
Re
The written essays close to this good topic composing could be a very time consuming action, but when you’re not a great expert, you have got a possibility to find the information associated with essay buying from the writing services effortless.
Sun, 2010-01-03, 09:37
#34
Re: Re
Does anyone other than me find the grammar in this spam message hilariously ironic?
Ishaaq
2010/1/3 SF31Amelia <SF31Amelia@yopmail.com>
Ishaaq
2010/1/3 SF31Amelia <SF31Amelia@yopmail.com>
The written essays close to this good topic composing could be a very time consuming action, but when you’re not a great expert, you have got a possibility to find the information associated with essay buying [1] from the writing services [2] effortless.
[1] http://bestwritingservice.com/essay-buying.html
[2] http://www.bestwritingservice.com
Sun, 2010-01-03, 17:27
#35
Re: Re
My theory: This might be a spambot seeding the e-mail filters with the sender's e-mail address, so that the address gets "whitelisted" and is able to send true spam later. I've seen some bots employing this technique in blog comments, so that the sending e-mail address gets whitelisted and the bot can later come back to post unfiltered spam.
Some spam filters are set up to automatically whitelist a sending e-mail address if two or more posts coming from the same e-mail address are approved by human monitors. The logic being that if two or more previous posts are not spam, then the sender is very unlikely to be a spambot.
This attack targets such filters -- the bot tries to send a couple innocuous-looking messages that look kind of like a real human could have written them. Note that all words in the original post have little or no spam association, so no Baysian spam filters would flag the post.
Another theory: the original post is from ZZaflodidic Quersh from the planet QQQ34^6, who's trying to make a little money on the side because his day job spying on the English-speaking Human Race doesn't pay enough.
Brian Maso
On Sun, Jan 3, 2010 at 12:29 AM, Ishaaq Chandy <ishaaq@gmail.com> wrote:
Some spam filters are set up to automatically whitelist a sending e-mail address if two or more posts coming from the same e-mail address are approved by human monitors. The logic being that if two or more previous posts are not spam, then the sender is very unlikely to be a spambot.
This attack targets such filters -- the bot tries to send a couple innocuous-looking messages that look kind of like a real human could have written them. Note that all words in the original post have little or no spam association, so no Baysian spam filters would flag the post.
Another theory: the original post is from ZZaflodidic Quersh from the planet QQQ34^6, who's trying to make a little money on the side because his day job spying on the English-speaking Human Race doesn't pay enough.
Brian Maso
On Sun, Jan 3, 2010 at 12:29 AM, Ishaaq Chandy <ishaaq@gmail.com> wrote:
Does anyone other than me find the grammar in this spam message hilariously ironic?
Ishaaq
2010/1/3 SF31Amelia <SF31Amelia@yopmail.com>
The written essays close to this good topic composing could be a very time consuming action, but when you’re not a great expert, you have got a possibility to find the information associated with essay buying [1] from the writing services [2] effortless.
[1] http://bestwritingservice.com/essay-buying.html
[2] http://www.bestwritingservice.com
Ask it the other way around. Does it make sense for them to be mutable?
Having them be immutable, caching becomes infinitely easier and safer.