Friday, April 13. 2007The Scala Option class and how lift uses itTrackbacks
Trackback specific URI for this entry
No Trackbacks
Comments
Display comments as
(Linear | Threaded)
Cool. This is basically the same as Haskell's "Maybe" monad.
http://www.randomhacks.net/articles/2007/03/12/monads-in-15-minutes
This seems incredibly non-obvious to me.
Why are you using a list operation for single values? What does the getOrElse refer to? id, user? What does it do if there is actually a list? Does swapping for-yield-getOrElse instead of if-if really improve things?
I found the whole Option stuff non-obvious for the first month+ of using Scala, so I know where you're coming from.
The for-yield-getOrElse stuff improves my code because it localizes all the variable setting and in general, after using the idiom (with years of if-if-if under my belt), the for-yield-getOrElse idiom feels more natural. The 'for' comprehension results in the same list type that was used in its elements, so if you have a bunch of Options, then you have an Option of whatever is yielded, or a None. The getOrElse either unpacks the Some(whatever was yielded) or if it's a None, executes the "else" block.
The "list operation" (for comprehension) is actually a monad operation, and so it makes sense for Option, which is a monad.
I too felt a bit uncomfortable to see that at first, but after learning a little about monads, I'm fine with it. The key point is that a for comprehension doesn't necessarily iterate over a collection - that depends on what the particular monad is.
A for comprehension where there is nothing to iterate looks weird to me as well. Maybe a better construct can be achieved, even if not as part of the language itself... just a thought. I don't know, I'm still too much of a scala newbie.
The for-yield-getOrElse stuff improves my code because it localizes all the variable setting and in general, after using the idiom (with years of if-if-if under my belt), the for-yield-getOrElse idiom feels more natural.I too felt a bit uncomfortable to see that at first, but after learning a little about monads, I'm fine with it.
The key point is that a for comprehension doesn't necessarily iterate over a collection - that depends on what the particular monad is.
Pattern matching is probably an alternative -- as a tuple with default case. I haven't used Scala recently, but something like:
(param("id"), User.find(param("id")) match { case (Some(id), Some(user)) => handle user stuff ... case _ => error stuff ... }
Assuming the pattern matching works and is effectively equivalent, I much prefer it! Seems more natural and readable.
Further discussion about the creation of "Some":
http://scala-forum.org/read.php?4,138 |
David PollakCalendar
QuicksearchCategoriesBlog Administration |
||||||||||||||||||||||||||||||||||||||||||