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

Why have method "get" in Option?

51 replies
Sean Leather
Joined: 2010-08-08,
User offline. Last seen 42 years 45 weeks ago.
Following on from some recent discussion on the design of Option and in my ongoing search to understand Scala, I have a fundamental question.

Why does the method "get" exist in the Option class? Here is the abbreviated code from scala/Option.scala.

sealed abstract class Option[+A] extends Product {
  def get: A
}

final case class Some[+A](x: A) extends Option[A] {
  def get = x
}

case object None extends Option[Nothing] {
  def get = throw new NoSuchElementException("None.get")
}

For reasons of type safety, shouldn't "get" only exist in Some? Or is this just another way of replacing "x.getOrElse(default)" with "try { x.get } catch { default }"?

Regards,
Sean
H-star Development
Joined: 2010-04-14,
User offline. Last seen 2 years 26 weeks ago.
Re: Why have method "get" in Option?

that would force you to cast option to some and every time you now do
{know that op is defined} op.get
would turn into
{know that op is defined} op.asInstanceOf[Some[MyType]].get

with no benefit because if {know that op is defined} is wrong, you'll just replace nosuchelement by a classcast.

-------- Original-Nachricht --------
> Datum: Fri, 13 Aug 2010 12:30:40 +0200
> Von: Sean Leather
> An: Scala Users Lists
> Betreff: [scala-user] Why have method "get" in Option?

> Following on from some recent discussion on the design of Option and in my
> ongoing search to understand Scala, I have a fundamental question.
>
> Why does the method "get" exist in the Option class? Here is the
> abbreviated
> code from scala/Option.scala.
>
> sealed abstract class Option[+A] extends Product {
> def get: A
> }
>
> final case class Some[+A](x: A) extends Option[A] {
> def get = x
> }
>
> case object None extends Option[Nothing] {
> def get = throw new NoSuchElementException("None.get")
> }
>
> For reasons of type safety, shouldn't "get" only exist in Some? Or is this
> just another way of replacing "x.getOrElse(default)" with "try { x.get }
> catch { default }"?
>
> Regards,
> Sean

Tony Morris 2
Joined: 2009-03-20,
User offline. Last seen 42 years 45 weeks ago.
Re: Why have method "get" in Option?

Hi Sean,
Your question can be generalised to, "why have partial functions?" The
answer is not because they are preferred, but because they are necessary
according to Turing's undecidability.

Some languages do away with turing-completeness in favour of totality
(that is, no partial functions). Examples are Coq and Agda.

This is related to the mistakes in the original article.

Sean Leather wrote:
> Following on from some recent discussion on the design of Option and
> in my ongoing search to understand Scala, I have a fundamental question.
>
> Why does the method "get" exist in the Option class? Here is the
> abbreviated code from scala/Option.scala.
>
> sealed abstract class Option[+A] extends Product {
> def get: A
> }
>
> final case class Some[+A](x: A) extends Option[A] {
> def get = x
> }
>
> case object None extends Option[Nothing] {
> def get = throw new NoSuchElementException("None.get")
> }
>
> For reasons of type safety, shouldn't "get" only exist in Some? Or is
> this just another way of replacing "x.getOrElse(default)" with "try {
> x.get } catch { default }"?
>
> Regards,
> Sean

Jesper
Joined: 2010-06-13,
User offline. Last seen 2 years 17 weeks ago.
Re: Why have method "get" in Option?
No, it wouldn't force you to cast, because you can use pattern matching instead of casting:
val opt: Option[X] = ...
opt match {  case Some(x) => println(x)   case None => println("None")}
(Note, you don't even have to call 'get', pattern matching gets the value out of the Option for you).
Jesper
2010/8/13 Dennis Haupt <h-star@gmx.de>
that would force you to cast option to some and every time you now do
{know that op is defined} op.get
would turn into
{know that op is defined} op.asInstanceOf[Some[MyType]].get

with no benefit because if {know that op is defined} is wrong, you'll just replace nosuchelement by a classcast.


-------- Original-Nachricht --------
> Datum: Fri, 13 Aug 2010 12:30:40 +0200
> Von: Sean Leather <leather@cs.uu.nl>
> An: Scala Users Lists <scala-user@listes.epfl.ch>
> Betreff: [scala-user] Why have method "get" in Option?

> Following on from some recent discussion on the design of Option and in my
> ongoing search to understand Scala, I have a fundamental question.
>
> Why does the method "get" exist in the Option class? Here is the
> abbreviated
> code from scala/Option.scala.
>
> sealed abstract class Option[+A] extends Product {
>   def get: A
> }
>
> final case class Some[+A](x: A) extends Option[A] {
>   def get = x
> }
>
> case object None extends Option[Nothing] {
>   def get = throw new NoSuchElementException("None.get")
> }
>
> For reasons of type safety, shouldn't "get" only exist in Some? Or is this
> just another way of replacing "x.getOrElse(default)" with "try { x.get }
> catch { default }"?
>
> Regards,
> Sean

--
GMX DSL SOMMER-SPECIAL: Surf & Phone Flat 16.000 für nur 19,99 ¿/mtl.!*
http://portal.gmx.net/de/go/dsl



--
Jesper de Jong
jespdj@gmail.com
Sciss
Joined: 2008-12-17,
User offline. Last seen 28 weeks 5 days ago.
Re: Why have method "get" in Option?

no, the question is valid. basically you should be able to get completely around with 'foreach', 'map' and 'getOrElse', thus 'get' is a really poor method that introduces potential runtime errors which would be impossible without this method. and thus, if you consider 'get' being not there, also the question of why not all the methods are in the subclasses of None and Some is totally accurate. i think that would have been cleaner (besides slightly faster) than the if( ....isDefined ) all over the Option class. the argumentation of "Algebraic data types" versus "Class hierarchies" misses the point IMO. Option is already sealed, so there can be only the two subclasses None and Some.

best, -sciss-

Am 13.08.2010 um 12:30 schrieb Dennis Haupt:

> that would force you to cast option to some and every time you now do
> {know that op is defined} op.get
> would turn into
> {know that op is defined} op.asInstanceOf[Some[MyType]].get
>
> with no benefit because if {know that op is defined} is wrong, you'll just replace nosuchelement by a classcast.
>
>
> -------- Original-Nachricht --------
>> Datum: Fri, 13 Aug 2010 12:30:40 +0200
>> Von: Sean Leather
>> An: Scala Users Lists
>> Betreff: [scala-user] Why have method "get" in Option?
>
>> Following on from some recent discussion on the design of Option and in my
>> ongoing search to understand Scala, I have a fundamental question.
>>
>> Why does the method "get" exist in the Option class? Here is the
>> abbreviated
>> code from scala/Option.scala.
>>
>> sealed abstract class Option[+A] extends Product {
>> def get: A
>> }
>>
>> final case class Some[+A](x: A) extends Option[A] {
>> def get = x
>> }
>>
>> case object None extends Option[Nothing] {
>> def get = throw new NoSuchElementException("None.get")
>> }
>>
>> For reasons of type safety, shouldn't "get" only exist in Some? Or is this
>> just another way of replacing "x.getOrElse(default)" with "try { x.get }
>> catch { default }"?
>>
>> Regards,
>> Sean
>

Daniel Degrandi
Joined: 2010-05-10,
User offline. Last seen 42 years 45 weeks ago.
Re: Why have method "get" in Option?
That is correct, but it was not the question. To use the method get you would have to cast to Some.

I think the get method is only useful in cases where you are 100% sure that you have a Some to make the whole thing more concise. Whenever you are unsure use pattern matching or getOrElse.

Dan

Jesper de Jong schrieb:
AANLkTimzOgGAyRzZuRqhTQd7cxL0KbypkDbaDE9LBtN3 [at] mail [dot] gmail [dot] com" type="cite">No, it wouldn't force you to cast, because you can use pattern matching instead of casting:
val opt: Option[X] = ...
opt match {   case Some(x) => println(x)   case None => println("None") }
(Note, you don't even have to call 'get', pattern matching gets the value out of the Option for you).
Jesper
2010/8/13 Dennis Haupt <h-star [at] gmx [dot] de" rel="nofollow">h-star@gmx.de>
that would force you to cast option to some and every time you now do
{know that op is defined} op.get
would turn into
{know that op is defined} op.asInstanceOf[Some[MyType]].get

with no benefit because if {know that op is defined} is wrong, you'll just replace nosuchelement by a classcast.


-------- Original-Nachricht --------
> Datum: Fri, 13 Aug 2010 12:30:40 +0200
> Von: Sean Leather <leather [at] cs [dot] uu [dot] nl" rel="nofollow">leather@cs.uu.nl>
> An: Scala Users Lists <scala-user [at] listes [dot] epfl [dot] ch" rel="nofollow">scala-user@listes.epfl.ch>
> Betreff: [scala-user] Why have method "get" in Option?

> Following on from some recent discussion on the design of Option and in my
> ongoing search to understand Scala, I have a fundamental question.
>
> Why does the method "get" exist in the Option class? Here is the
> abbreviated
> code from scala/Option.scala.
>
> sealed abstract class Option[+A] extends Product {
>   def get: A
> }
>
> final case class Some[+A](x: A) extends Option[A] {
>   def get = x
> }
>
> case object None extends Option[Nothing] {
>   def get = throw new NoSuchElementException("None.get")
> }
>
> For reasons of type safety, shouldn't "get" only exist in Some? Or is this
> just another way of replacing "x.getOrElse(default)" with "try { x.get }
> catch { default }"?
>
> Regards,
> Sean

--
GMX DSL SOMMER-SPECIAL: Surf & Phone Flat 16.000 für nur 19,99 ¿/mtl.!*
http://portal.gmx.net/de/go/dsl



Sean Leather
Joined: 2010-08-08,
User offline. Last seen 42 years 45 weeks ago.
Re: Why have method "get" in Option?
Thanks for the response. There are quite a few replies here, and I'm certain I don't understand most. As a result, I will try to clarify my question.

Why does the method "get" exist in the Option class?

The point of this question is that the method "get" is by definition unsafe. By unsafe, I mean that it will likely lead a programmer who uses it into error. Why is it unsafe? Let's review the code:
 
sealed abstract class Option[+A] extends Product { def get: A }
final case class Some[+A](x: A) extends Option[A] { def get = x }
case object None extends Option[Nothing] { def get = throw new NoSuchElementException("None.get") }

Since "get" is defined in the class Option, there is an implication that each subclass will override it and return some A value. Looking at each inheritor, we see that Some overrides and results in a value, but None throws an exception. Since there are only two subclasses and half of them are exceptional cases, I'd say it's pretty clear that "get" will lead somebody into error. Thus, it is unsafe.

For reasons of type safety, shouldn't "get" only exist in Some? Or is this just another way of replacing "x.getOrElse(default)" with "try { x.get } catch { default }"?

I'm suggesting that "get" not be defined in Option but rather in Some. That provides one way to get the value out of Some. But how do you get the value out of an Option? Again, I'm new to Scala but I already see multiple ways:
  • getOrElse
  • foreach/for
  • iterator
  • opt match { case Some(x) => ... ; case None => ... }
And I'm sure there are others.

Of course, this is not to say that a method equivalent to "get" can't still be written outside of Option.

def fromSome(opt: Option[A]) = opt match {
  case Some(x) => x
  case None => throw new NoSuchElementException("fromSome")
}

However, by putting "Option.get" (and even "orNull" and possibly others) in the standard library, it encourages programmers to use unsafe methods by making it easy. I get the impression that such unsafe methods are generally included in the Scala libraries. So, I suppose my real question should be: Why are unsafe methods included in the standard libraries?

Regards,
Sean
nilskp
Joined: 2009-01-30,
User offline. Last seen 1 year 27 weeks ago.
Re: Why have method "get" in Option?
On Fri, Aug 13, 2010 at 6:38 AM, Sciss <contact@sciss.de> wrote:
no, the question is valid. basically you should be able to get completely around with 'foreach', 'map' and 'getOrElse', thus 'get' is a really poor method that introduces potential runtime errors which would be impossible without this method.

In the cases I use 'get' without checking I *want* a runtime error. It means I made a wrong assumption in my code and it better fail fast.

Patrik Andersson
Joined: 2009-11-16,
User offline. Last seen 42 years 45 weeks ago.
Re: Re: Why have method "get" in Option?
But get is not any more unsafe than dereferencing any non-final (e.g. val) reference. As I've said in one of the other Option threads - it's not Options / nullabilities fault that we have NoSuchElementException / NPE:s, it's bad assumptions. Bad assumptions don't go away because you take away get. You could just aswell do foreach on an Option not accounting for the fact that in your particular use-case you also need to handle the None-case. Bad assumption.
Structure the code in such a way that there are no assumptions that cannot be 100% trusted.

On Fri, Aug 13, 2010 at 2:37 PM, Sean Leather <leather@cs.uu.nl> wrote:
Thanks for the response. There are quite a few replies here, and I'm certain I don't understand most. As a result, I will try to clarify my question.

Why does the method "get" exist in the Option class?

The point of this question is that the method "get" is by definition unsafe. By unsafe, I mean that it will likely lead a programmer who uses it into error. Why is it unsafe? Let's review the code:
 
sealed abstract class Option[+A] extends Product { def get: A }
final case class Some[+A](x: A) extends Option[A] { def get = x }
case object None extends Option[Nothing] { def get = throw new NoSuchElementException("None.get") }

Since "get" is defined in the class Option, there is an implication that each subclass will override it and return some A value. Looking at each inheritor, we see that Some overrides and results in a value, but None throws an exception. Since there are only two subclasses and half of them are exceptional cases, I'd say it's pretty clear that "get" will lead somebody into error. Thus, it is unsafe.

For reasons of type safety, shouldn't "get" only exist in Some? Or is this just another way of replacing "x.getOrElse(default)" with "try { x.get } catch { default }"?

I'm suggesting that "get" not be defined in Option but rather in Some. That provides one way to get the value out of Some. But how do you get the value out of an Option? Again, I'm new to Scala but I already see multiple ways:
  • getOrElse
  • foreach/for
  • iterator
  • opt match { case Some(x) => ... ; case None => ... }
And I'm sure there are others.

Of course, this is not to say that a method equivalent to "get" can't still be written outside of Option.

def fromSome(opt: Option[A]) = opt match {
  case Some(x) => x
  case None => throw new NoSuchElementException("fromSome")
}

However, by putting "Option.get" (and even "orNull" and possibly others) in the standard library, it encourages programmers to use unsafe methods by making it easy. I get the impression that such unsafe methods are generally included in the Scala libraries. So, I suppose my real question should be: Why are unsafe methods included in the standard libraries?

Regards,
Sean

ichoran
Joined: 2009-08-14,
User offline. Last seen 2 years 3 weeks ago.
Re: Why have method "get" in Option?
On Fri, Aug 13, 2010 at 6:30 AM, Sean Leather <leather@cs.uu.nl> wrote:
Following on from some recent discussion on the design of Option and in my ongoing search to understand Scala, I have a fundamental question.

Why does the method "get" exist in the Option class?


It exists so you can do things like this:

// Example 1: You know it will succeed, why check again?
def f(o: Option[Int]) = o map (i => i + i*i)
f(Some(7)).get

// Example 2: Usually don't need the value, why pattern-match?
def g(o: Option[Int], rare_condition: Boolean) {
  if (o.isDefined) {
    println("All sorts of stuff happens here")
    if (rare_condition) println( o.get )
    println("More stuff happens here")
  }
  else {
    println("Various stuff here")
  }
}

// Example 3: We're prototyping here--let's not error-check every case yet
def h(command_line_argument: Option[String]) {
  println("User asked for: " + command_line_argument.get)
}

The coder's job is know when get is the appropriate method, and when they should use something else.

  --Rex

H-star Development
Joined: 2010-04-14,
User offline. Last seen 2 years 26 weeks ago.
Re: Why have method "get" in Option?

that just hides the cast, and it's even longer than using a cast or getOrElse directly.

i still vote for a simple "get"

-------- Original-Nachricht --------
> Datum: Fri, 13 Aug 2010 13:46:27 +0200
> Von: Jesper de Jong
> An: scala-user
> Betreff: Re: [scala-user] Why have method "get" in Option?

> No, it wouldn't force you to cast, because you can use pattern matching
> instead of casting:
>
> val opt: Option[X] = ...
>
> opt match {
> case Some(x) => println(x)
> case None => println("None")
> }
>
> (Note, you don't even have to call 'get', pattern matching gets the value
> out of the Option for you).
>
> Jesper
>
> 2010/8/13 Dennis Haupt
>
> > that would force you to cast option to some and every time you now do
> > {know that op is defined} op.get
> > would turn into
> > {know that op is defined} op.asInstanceOf[Some[MyType]].get
> >
> > with no benefit because if {know that op is defined} is wrong, you'll
> just
> > replace nosuchelement by a classcast.
> >
> >
> > -------- Original-Nachricht --------
> > > Datum: Fri, 13 Aug 2010 12:30:40 +0200
> > > Von: Sean Leather
> > > An: Scala Users Lists
> > > Betreff: [scala-user] Why have method "get" in Option?
> >
> > > Following on from some recent discussion on the design of Option and
> in
> > my
> > > ongoing search to understand Scala, I have a fundamental question.
> > >
> > > Why does the method "get" exist in the Option class? Here is the
> > > abbreviated
> > > code from scala/Option.scala.
> > >
> > > sealed abstract class Option[+A] extends Product {
> > > def get: A
> > > }
> > >
> > > final case class Some[+A](x: A) extends Option[A] {
> > > def get = x
> > > }
> > >
> > > case object None extends Option[Nothing] {
> > > def get = throw new NoSuchElementException("None.get")
> > > }
> > >
> > > For reasons of type safety, shouldn't "get" only exist in Some? Or is
> > this
> > > just another way of replacing "x.getOrElse(default)" with "try { x.get
> }
> > > catch { default }"?
> > >
> > > Regards,
> > > Sean
> >
> > --
> > GMX DSL SOMMER-SPECIAL: Surf & Phone Flat 16.000 für nur 19,99
> ¿/mtl.!*
> > http://portal.gmx.net/de/go/dsl
> >
>
>
>

Kris Nuttycombe
Joined: 2009-01-16,
User offline. Last seen 42 years 45 weeks ago.
Re: Why have method "get" in Option?

I think that the presence of 'get' in Option (rather than Some) is
unfortunate as well. It defeats the purpose of using Option in the
first place, and as such I never use it.

With respect to the example:

// Example 1: You know it will succeed, why check again?
def f(o: Option[Int]) = o map (i => i + i*i)
f(Some(7)).get

I thought that there might be a solution to this in a definition like:

scala> def f[T <: Option[Int]](o: T): T = o.map(i => i + i*i)
:5: error: type mismatch;
found : Option[Int]
required: T

but it appears that the type of map does not specialize adequately (at
least with this construction.) I was surprised when I went to the
scaladoc to find that Option doesn't extend from TraversableLike. This
seems very odd to me - it means that this kind of construction fails
too:

scala> for (v <- Some(2); v2 <- List(4, 5, 6)) yield v * v2
:6: error: type mismatch;
found : List[Int]
required: Option[?]
for (v <- Some(2); v2 <- List(4, 5, 6)) yield v * v2
^

Yuck! Why is Option a second-class citizen???

Kris

On Fri, Aug 13, 2010 at 8:34 AM, Dennis Haupt wrote:
> that just hides the cast, and it's even longer than using a cast or getOrElse directly.
>
> i still vote for a simple "get"
>
> -------- Original-Nachricht --------
>> Datum: Fri, 13 Aug 2010 13:46:27 +0200
>> Von: Jesper de Jong
>> An: scala-user
>> Betreff: Re: [scala-user] Why have method "get" in Option?
>
>> No, it wouldn't force you to cast, because you can use pattern matching
>> instead of casting:
>>
>> val opt: Option[X] = ...
>>
>> opt match {
>>   case Some(x) => println(x)
>>   case None => println("None")
>> }
>>
>> (Note, you don't even have to call 'get', pattern matching gets the value
>> out of the Option for you).
>>
>> Jesper
>>
>> 2010/8/13 Dennis Haupt
>>
>> > that would force you to cast option to some and every time you now do
>> > {know that op is defined} op.get
>> > would turn into
>> > {know that op is defined} op.asInstanceOf[Some[MyType]].get
>> >
>> > with no benefit because if {know that op is defined} is wrong, you'll
>> just
>> > replace nosuchelement by a classcast.
>> >
>> >
>> > -------- Original-Nachricht --------
>> > > Datum: Fri, 13 Aug 2010 12:30:40 +0200
>> > > Von: Sean Leather
>> > > An: Scala Users Lists
>> > > Betreff: [scala-user] Why have method "get" in Option?
>> >
>> > > Following on from some recent discussion on the design of Option and
>> in
>> > my
>> > > ongoing search to understand Scala, I have a fundamental question.
>> > >
>> > > Why does the method "get" exist in the Option class? Here is the
>> > > abbreviated
>> > > code from scala/Option.scala.
>> > >
>> > > sealed abstract class Option[+A] extends Product {
>> > >   def get: A
>> > > }
>> > >
>> > > final case class Some[+A](x: A) extends Option[A] {
>> > >   def get = x
>> > > }
>> > >
>> > > case object None extends Option[Nothing] {
>> > >   def get = throw new NoSuchElementException("None.get")
>> > > }
>> > >
>> > > For reasons of type safety, shouldn't "get" only exist in Some? Or is
>> > this
>> > > just another way of replacing "x.getOrElse(default)" with "try { x.get
>> }
>> > > catch { default }"?
>> > >
>> > > Regards,
>> > > Sean
>> >
>> > --
>> > GMX DSL SOMMER-SPECIAL: Surf & Phone Flat 16.000 für nur 19,99
>> ¿/mtl.!*
>> > http://portal.gmx.net/de/go/dsl
>> >
>>
>>
>>
>> --
>> Jesper de Jong
>> jespdj@gmail.com
>
> --
> GMX DSL SOMMER-SPECIAL: Surf & Phone Flat 16.000 für nur 19,99 ¿/mtl.!*
> http://portal.gmx.net/de/go/dsl
>

extempore
Joined: 2008-12-17,
User offline. Last seen 35 weeks 3 days ago.
Re: Why have method "get" in Option?

On Fri, Aug 13, 2010 at 12:58:14PM -0600, Kris Nuttycombe wrote:
> Yuck! Why is Option a second-class citizen???

The most recent of many trips around that maypole:

http://scala-programming-language.1934581.n4.nabble.com/Why-does-Option-...

There are lengthier ones, but that one is probably enough for you.

H-star Development
Joined: 2010-04-14,
User offline. Last seen 2 years 26 weeks ago.
Re: Why have method "get" in Option?

i think you misunderstood the purpose of map on option.
it maps Some(x) to Some(y) and None to None. the mapping function can be
applied to any option, no matter if it's some or none. you don't have to
check if option is defined. it's not meant to get the value out of a some.

and maybe you misunderstood the option itself. i use it as a return type
where there might be no valid result. for example, if i call
"findPath(from:Position, to:Position), the return type is Option[Path].
if there is a path i get some, if there is none, i get None.
now i want to render that path:
result.foreach(_.renderOnScreen)
no need to check for null. the function is executed if there is a path,
otherwise nothing is going to happen.

Am 13.08.2010 20:58, schrieb Kris Nuttycombe:
> I think that the presence of 'get' in Option (rather than Some) is
> unfortunate as well. It defeats the purpose of using Option in the
> first place, and as such I never use it.
>
> With respect to the example:
>
> // Example 1: You know it will succeed, why check again?
> def f(o: Option[Int]) = o map (i => i + i*i)
> f(Some(7)).get
>
> I thought that there might be a solution to this in a definition like:
>
> scala> def f[T <: Option[Int]](o: T): T = o.map(i => i + i*i)
> :5: error: type mismatch;
> found : Option[Int]
> required: T
>
> but it appears that the type of map does not specialize adequately (at
> least with this construction.) I was surprised when I went to the
> scaladoc to find that Option doesn't extend from TraversableLike. This
> seems very odd to me - it means that this kind of construction fails
> too:
>
> scala> for (v <- Some(2); v2 <- List(4, 5, 6)) yield v * v2
> :6: error: type mismatch;
> found : List[Int]
> required: Option[?]
> for (v <- Some(2); v2 <- List(4, 5, 6)) yield v * v2
> ^
>
> Yuck! Why is Option a second-class citizen???
>
> Kris
>
>
>
> On Fri, Aug 13, 2010 at 8:34 AM, Dennis Haupt wrote:
>> that just hides the cast, and it's even longer than using a cast or getOrElse directly.
>>
>> i still vote for a simple "get"
>>
>> -------- Original-Nachricht --------
>>> Datum: Fri, 13 Aug 2010 13:46:27 +0200
>>> Von: Jesper de Jong
>>> An: scala-user
>>> Betreff: Re: [scala-user] Why have method "get" in Option?
>>> No, it wouldn't force you to cast, because you can use pattern matching
>>> instead of casting:
>>>
>>> val opt: Option[X] = ...
>>>
>>> opt match {
>>> case Some(x) => println(x)
>>> case None => println("None")
>>> }
>>>
>>> (Note, you don't even have to call 'get', pattern matching gets the value
>>> out of the Option for you).
>>>
>>> Jesper
>>>
>>> 2010/8/13 Dennis Haupt
>>>
>>>> that would force you to cast option to some and every time you now do
>>>> {know that op is defined} op.get
>>>> would turn into
>>>> {know that op is defined} op.asInstanceOf[Some[MyType]].get
>>>>
>>>> with no benefit because if {know that op is defined} is wrong, you'll
>>> just
>>>> replace nosuchelement by a classcast.
>>>>
>>>>
>>>> -------- Original-Nachricht --------
>>>>> Datum: Fri, 13 Aug 2010 12:30:40 +0200
>>>>> Von: Sean Leather
>>>>> An: Scala Users Lists
>>>>> Betreff: [scala-user] Why have method "get" in Option?
>>>>> Following on from some recent discussion on the design of Option and
>>> in
>>>> my
>>>>> ongoing search to understand Scala, I have a fundamental question.
>>>>>
>>>>> Why does the method "get" exist in the Option class? Here is the
>>>>> abbreviated
>>>>> code from scala/Option.scala.
>>>>>
>>>>> sealed abstract class Option[+A] extends Product {
>>>>> def get: A
>>>>> }
>>>>>
>>>>> final case class Some[+A](x: A) extends Option[A] {
>>>>> def get = x
>>>>> }
>>>>>
>>>>> case object None extends Option[Nothing] {
>>>>> def get = throw new NoSuchElementException("None.get")
>>>>> }
>>>>>
>>>>> For reasons of type safety, shouldn't "get" only exist in Some? Or is
>>>> this
>>>>> just another way of replacing "x.getOrElse(default)" with "try { x.get
>>> }
>>>>> catch { default }"?
>>>>>
>>>>> Regards,
>>>>> Sean
>>>> --
>>>> GMX DSL SOMMER-SPECIAL: Surf & Phone Flat 16.000 für nur 19,99
>>> ¿/mtl.!*
>>>> http://portal.gmx.net/de/go/dsl
>>>>
>>>
>>>
>>> --
>>> Jesper de Jong
>>> jespdj@gmail.com
>> --
>> GMX DSL SOMMER-SPECIAL: Surf & Phone Flat 16.000 für nur 19,99 ¿/mtl.!*
>> http://portal.gmx.net/de/go/dsl
>>

Kris Nuttycombe
Joined: 2009-01-16,
User offline. Last seen 42 years 45 weeks ago.
Re: Why have method "get" in Option?

Hah. I understand the purpose of map quite well, thanks. Perhaps you
should look at my question (and the applicability of TraversableLike)
a little more closely.

If Option were to extend TraversableLike, then it would be possible to
"trace" whether an Option instance were a Some or a None through a a
call to map, and have a safe implementation of get.

But, then, as Paulp's link demonstrates, flatMap would be broken. So
it's not a reasonable idea after all.

:)

Kris

On Fri, Aug 13, 2010 at 1:21 PM, HamsterofDeath wrote:
>  i think you misunderstood the purpose of map on option.
> it maps Some(x) to Some(y) and None to None. the mapping function can be
> applied to any option, no matter if it's some or none. you don't have to
> check if option is defined. it's not meant to get the value out of a some.
>
> and maybe you misunderstood the option itself. i use it as a return type
> where there might be no valid result. for example, if i call
> "findPath(from:Position, to:Position), the return type is Option[Path].
> if there is a path i get some, if there is none, i get None.
> now i want to render that path:
> result.foreach(_.renderOnScreen)
> no need to check for null. the function is executed if there is a path,
> otherwise nothing is going to happen.
>
>
>
>
>
> Am 13.08.2010 20:58, schrieb Kris Nuttycombe:
>> I think that the presence of 'get' in Option (rather than Some) is
>> unfortunate as well. It defeats the purpose of using Option in the
>> first place, and as such I never use it.
>>
>> With respect to the example:
>>
>> // Example 1: You know it will succeed, why check again?
>> def f(o: Option[Int]) = o map (i => i + i*i)
>> f(Some(7)).get
>>
>> I thought that there might be a solution to this in a definition like:
>>
>> scala> def f[T <: Option[Int]](o: T): T = o.map(i => i + i*i)
>> :5: error: type mismatch;
>>  found   : Option[Int]
>>  required: T
>>
>> but it appears that the type of map does not specialize adequately (at
>> least with this construction.) I was surprised when I went to the
>> scaladoc to find that Option doesn't extend from TraversableLike. This
>> seems very odd to me - it means that this kind of construction fails
>> too:
>>
>> scala> for (v <- Some(2); v2 <- List(4, 5, 6)) yield v * v2
>> :6: error: type mismatch;
>>  found   : List[Int]
>>  required: Option[?]
>>        for (v <- Some(2); v2 <- List(4, 5, 6)) yield v * v2
>>                              ^
>>
>> Yuck! Why is Option a second-class citizen???
>>
>> Kris
>>
>>
>>
>> On Fri, Aug 13, 2010 at 8:34 AM, Dennis Haupt wrote:
>>> that just hides the cast, and it's even longer than using a cast or getOrElse directly.
>>>
>>> i still vote for a simple "get"
>>>
>>> -------- Original-Nachricht --------
>>>> Datum: Fri, 13 Aug 2010 13:46:27 +0200
>>>> Von: Jesper de Jong
>>>> An: scala-user
>>>> Betreff: Re: [scala-user] Why have method "get" in Option?
>>>> No, it wouldn't force you to cast, because you can use pattern matching
>>>> instead of casting:
>>>>
>>>> val opt: Option[X] = ...
>>>>
>>>> opt match {
>>>>   case Some(x) => println(x)
>>>>   case None => println("None")
>>>> }
>>>>
>>>> (Note, you don't even have to call 'get', pattern matching gets the value
>>>> out of the Option for you).
>>>>
>>>> Jesper
>>>>
>>>> 2010/8/13 Dennis Haupt
>>>>
>>>>> that would force you to cast option to some and every time you now do
>>>>> {know that op is defined} op.get
>>>>> would turn into
>>>>> {know that op is defined} op.asInstanceOf[Some[MyType]].get
>>>>>
>>>>> with no benefit because if {know that op is defined} is wrong, you'll
>>>> just
>>>>> replace nosuchelement by a classcast.
>>>>>
>>>>>
>>>>> -------- Original-Nachricht --------
>>>>>> Datum: Fri, 13 Aug 2010 12:30:40 +0200
>>>>>> Von: Sean Leather
>>>>>> An: Scala Users Lists
>>>>>> Betreff: [scala-user] Why have method "get" in Option?
>>>>>> Following on from some recent discussion on the design of Option and
>>>> in
>>>>> my
>>>>>> ongoing search to understand Scala, I have a fundamental question.
>>>>>>
>>>>>> Why does the method "get" exist in the Option class? Here is the
>>>>>> abbreviated
>>>>>> code from scala/Option.scala.
>>>>>>
>>>>>> sealed abstract class Option[+A] extends Product {
>>>>>>   def get: A
>>>>>> }
>>>>>>
>>>>>> final case class Some[+A](x: A) extends Option[A] {
>>>>>>   def get = x
>>>>>> }
>>>>>>
>>>>>> case object None extends Option[Nothing] {
>>>>>>   def get = throw new NoSuchElementException("None.get")
>>>>>> }
>>>>>>
>>>>>> For reasons of type safety, shouldn't "get" only exist in Some? Or is
>>>>> this
>>>>>> just another way of replacing "x.getOrElse(default)" with "try { x.get
>>>> }
>>>>>> catch { default }"?
>>>>>>
>>>>>> Regards,
>>>>>> Sean
>>>>> --
>>>>> GMX DSL SOMMER-SPECIAL: Surf & Phone Flat 16.000 für nur 19,99
>>>> ¿/mtl.!*
>>>>> http://portal.gmx.net/de/go/dsl
>>>>>
>>>>
>>>>
>>>> --
>>>> Jesper de Jong
>>>> jespdj@gmail.com
>>> --
>>> GMX DSL SOMMER-SPECIAL: Surf & Phone Flat 16.000 für nur 19,99 ¿/mtl.!*
>>> http://portal.gmx.net/de/go/dsl
>>>
>
>

Jesper
Joined: 2010-06-13,
User offline. Last seen 2 years 17 weeks ago.
Re: Why have method "get" in Option?
No, when you pattern match, there is no cast at all, and no possibility that a ClassCastException will happen (which is why a cast is bad). Pattern matching is not a "hidden cast".
Jesper

2010/8/13 Dennis Haupt <h-star@gmx.de>
that just hides the cast, and it's even longer than using a cast or getOrElse directly.

i still vote for a simple "get"

-------- Original-Nachricht --------
> Datum: Fri, 13 Aug 2010 13:46:27 +0200
> Von: Jesper de Jong <jespdj@gmail.com>
> An: scala-user <scala-user@listes.epfl.ch>
> Betreff: Re: [scala-user] Why have method "get" in Option?

> No, it wouldn't force you to cast, because you can use pattern matching
> instead of casting:
>
> val opt: Option[X] = ...
>
> opt match {
>   case Some(x) => println(x)
>   case None => println("None")
> }
>
> (Note, you don't even have to call 'get', pattern matching gets the value
> out of the Option for you).
>
> Jesper
>
> 2010/8/13 Dennis Haupt <h-star@gmx.de>
>
> > that would force you to cast option to some and every time you now do
> > {know that op is defined} op.get
> > would turn into
> > {know that op is defined} op.asInstanceOf[Some[MyType]].get
> >
> > with no benefit because if {know that op is defined} is wrong, you'll
> just
> > replace nosuchelement by a classcast.
> >
> >
> > -------- Original-Nachricht --------
> > > Datum: Fri, 13 Aug 2010 12:30:40 +0200
> > > Von: Sean Leather <leather@cs.uu.nl>
> > > An: Scala Users Lists <scala-user@listes.epfl.ch>
> > > Betreff: [scala-user] Why have method "get" in Option?
> >
> > > Following on from some recent discussion on the design of Option and
> in
> > my
> > > ongoing search to understand Scala, I have a fundamental question.
> > >
> > > Why does the method "get" exist in the Option class? Here is the
> > > abbreviated
> > > code from scala/Option.scala.
> > >
> > > sealed abstract class Option[+A] extends Product {
> > >   def get: A
> > > }
> > >
> > > final case class Some[+A](x: A) extends Option[A] {
> > >   def get = x
> > > }
> > >
> > > case object None extends Option[Nothing] {
> > >   def get = throw new NoSuchElementException("None.get")
> > > }
> > >
> > > For reasons of type safety, shouldn't "get" only exist in Some? Or is
> > this
> > > just another way of replacing "x.getOrElse(default)" with "try { x.get
> }
> > > catch { default }"?
> > >
> > > Regards,
> > > Sean
> >
> > --
> > GMX DSL SOMMER-SPECIAL: Surf & Phone Flat 16.000 für nur 19,99
> ¿/mtl.!*
> > http://portal.gmx.net/de/go/dsl
> >
>
>
>
> --
> Jesper de Jong
> jespdj@gmail.com

--
GMX DSL SOMMER-SPECIAL: Surf & Phone Flat 16.000 für nur 19,99 ¿/mtl.!*
http://portal.gmx.net/de/go/dsl



--
Jesper de Jong
jespdj@gmail.com
Randall R Schulz
Joined: 2008-12-16,
User offline. Last seen 1 year 29 weeks ago.
Re: Why have method "get" in Option?

On Friday August 13 2010, Jesper de Jong wrote:
> No, when you pattern match, there is no cast at all, and no
> possibility that a ClassCastException will happen (which is why a
> cast is bad). Pattern matching is not a "hidden cast".

It is a cast.

It's just that the asInstanceOf is reliably
conditioned upon a preceding isInstanceOf
(their JVM bytecode equivalents, anyway).

> Jesper

Randall Schulz

Tony Morris 2
Joined: 2009-03-20,
User offline. Last seen 42 years 45 weeks ago.
Re: Re: Why have method "get" in Option?

Sean,
Scala *must* have unsafe methods. It's absolutely necessary. Nothing is
solved by moving or removing the get function in this respect.

Sean Leather wrote:
> Thanks for the response. There are quite a few replies here, and I'm
> certain I don't understand most. As a result, I will try to clarify my
> question.
>
> Why does the method "get" exist in the Option class?
>
>
> The point of this question is that the method "get" is by definition
> unsafe. By unsafe, I mean that it will likely lead a programmer who
> uses it into error. Why is it unsafe? Let's review the code:
>
>
> sealed abstract class Option[+A] extends Product { def get: A }
> final case class Some[+A](x: A) extends Option[A] { def get = x }
> case object None extends Option[Nothing] { def get = throw new
> NoSuchElementException("None.get") }
>
>
> Since "get" is defined in the class Option, there is an implication
> that each subclass will override it and return some A value. Looking
> at each inheritor, we see that Some overrides and results in a value,
> but None throws an exception. Since there are only two subclasses and
> half of them are exceptional cases, I'd say it's pretty clear that
> "get" will lead somebody into error. Thus, it is unsafe.
>
> For reasons of type safety, shouldn't "get" only exist in Some? Or
> is this just another way of replacing "x.getOrElse(default)" with
> "try { x.get } catch { default }"?
>
>
> I'm suggesting that "get" not be defined in Option but rather in Some.
> That provides one way to get the value out of Some. But how do you get
> the value out of an Option? Again, I'm new to Scala but I already see
> multiple ways:
>
> * getOrElse
> * foreach/for
> * iterator
> * opt match { case Some(x) => ... ; case None => ... }
>
> And I'm sure there are others.
>
> Of course, this is not to say that a method equivalent to "get" can't
> still be written outside of Option.
>
> def fromSome(opt: Option[A]) = opt match {
> case Some(x) => x
> case None => throw new NoSuchElementException("fromSome")
> }
>
> However, by putting "Option.get" (and even "orNull" and possibly
> others) in the standard library, it encourages programmers to use
> unsafe methods by making it easy. I get the impression that such
> unsafe methods are generally included in the Scala libraries. So, I
> suppose my real question should be: Why are unsafe methods included in
> the standard libraries?
>
> Regards,
> Sean

Sebastien Bocq
Joined: 2008-12-18,
User offline. Last seen 42 years 45 weeks ago.
Re: Why have method "get" in Option?
sealed abstract class Opt[+A] extends Iterable[A]
case object Non extends Opt[Nothing] {
    def iterator: Iterator[Nothing] = Iterator.empty
    def map[B](f:Nothing => B):Opt[B] = Non
    def flatMap[B](f:Nothing => Opt[B]):Opt[B] = Non
    override def filter(p:Nothing => Boolean):Opt[Nothing] = Non
}
case class Som[+A](a:A) extends Opt[A] {
    def iterator: Iterator[A] = Iterator.single(a)
    def map[B](f:A => B):Opt[B] = Som(f(a))
    def flatMap[B](f:A => Opt[B]):Opt[B] = f(a)
    override def filter(p:A => Boolean):Opt[A] = if (p(a)) this else Non
}

object Opt {
  def main(args : Array[String]) : Unit = {
      println(Som(1) flatMap{_:Int => Som(1)})          // Som(1)
      println(Som(1) flatMap{_:Int => Iterable(1, 2)})  // List(1, 2)

      println(for {
           y <- List(1, 2)
           x:Int <- Som(y)
      } yield (x,  y)) // List((1,1), (2,2))
     
  }
}

What is wrong with that?

Thanks,
Sebastien

2010/8/13 Paul Phillips <paulp@improving.org>
On Fri, Aug 13, 2010 at 12:58:14PM -0600, Kris Nuttycombe wrote:
> Yuck! Why is Option a second-class citizen???

The most recent of many trips around that maypole:

http://scala-programming-language.1934581.n4.nabble.com/Why-does-Option-not-extend-the-Iterable-trait-td1944949.html

There are lengthier ones, but that one is probably enough for you.

--
Paul Phillips      | Adultery is the application of democracy to love.
Caged Spirit       |     -- H. L. Mencken
Empiricist         |
i pull his palp!   |----------* http://www.improving.org/paulp/ *----------

Egon Nijns
Joined: 2010-05-19,
User offline. Last seen 42 years 45 weeks ago.
RE: Re: Why have method "get" in Option?

Tony,

Please elaborate on this. I'm not seeing the necessity.

Kind regards,
Egon.

Tony Morris wrote:

Sean,
Scala *must* have unsafe methods. It's absolutely necessary. Nothing is
solved by moving or removing the get function in this respect.

Sean Leather wrote:
> Thanks for the response. There are quite a few replies here, and I'm
> certain I don't understand most. As a result, I will try to clarify my
> question.
>
> Why does the method "get" exist in the Option class?
>
>
> The point of this question is that the method "get" is by definition
> unsafe. By unsafe, I mean that it will likely lead a programmer who
> uses it into error. Why is it unsafe? Let's review the code:
>
>
> sealed abstract class Option[+A] extends Product { def get: A }
> final case class Some[+A](x: A) extends Option[A] { def get = x }
> case object None extends Option[Nothing] { def get = throw new
> NoSuchElementException("None.get") }
>
>
> Since "get" is defined in the class Option, there is an implication
> that each subclass will override it and return some A value. Looking
> at each inheritor, we see that Some overrides and results in a value,
> but None throws an exception. Since there are only two subclasses and
> half of them are exceptional cases, I'd say it's pretty clear that
> "get" will lead somebody into error. Thus, it is unsafe.
>
> For reasons of type safety, shouldn't "get" only exist in Some? Or
> is this just another way of replacing "x.getOrElse(default)" with
> "try { x.get } catch { default }"?
>
>
> I'm suggesting that "get" not be defined in Option but rather in Some.
> That provides one way to get the value out of Some. But how do you get
> the value out of an Option? Again, I'm new to Scala but I already see
> multiple ways:
>
> * getOrElse
> * foreach/for
> * iterator
> * opt match { case Some(x) => ... ; case None => ... }
>
> And I'm sure there are others.
>
> Of course, this is not to say that a method equivalent to "get" can't
> still be written outside of Option.
>
> def fromSome(opt: Option[A]) = opt match {
> case Some(x) => x
> case None => throw new NoSuchElementException("fromSome")
> }
>
> However, by putting "Option.get" (and even "orNull" and possibly
> others) in the standard library, it encourages programmers to use
> unsafe methods by making it easy. I get the impression that such
> unsafe methods are generally included in the Scala libraries. So, I
> suppose my real question should be: Why are unsafe methods included in
> the standard libraries?
>
> Regards,
> Sean

Tony Morris 2
Joined: 2009-03-20,
User offline. Last seen 42 years 45 weeks ago.
Re: Re: Why have method "get" in Option?

Hello Egon,
The get method is alleged to be objectionable because it is a partial
function. Specifically, it is undefined for at least one element of its
domain (namely None). This idea of "undefinedness" is often denoted
several ways:
* undefined
* non-terminating computation
* bottom
* logical absurdity (more on this below)
* ⊥
*

Let's take a little excursion into the "logical absurdity" notation.
What does this mean? It means this...

The following proposition is false:

"Option[A] => A"

But what does this mean exactly? To say it out loud, "for all values A,
then Option[A] implies A is a false statement." The next question is,
but what exactly is Option? Well, it's a data type with two constructors
(None and Some), but it can also be represented this way:

trait Option[A] {
def fold[X](none: => X, some: A => X): X
}

In other words, the above trait is *exactly equivalent* to scala.Option.
I'm not going to show why in any detail, so please take my word for it
for now. Any function you can write with scala.Option I can write with
my.Option and vice versa -- they are isomorphic -- I did this by
exploiting the catamorphism for Option (note that passing None and Some
to fold gives you an identity function). This is a fun side-exercise if
you're keen; write the entire Option API using this one abstract method
fold -- I assure you it can be done, there is no trick.

So anyway, now we can safely change our proposition and we are still
saying the same thing:

forall A. (forall X. (X, A => X) => X) => A is a false statement.

You can observe the falsity of this proposition by drawing up a truth
table. Note that tupling is equivalent to logical conjunction (AND),
whose truth table I am sure you are familiar with. Here is the truth
table for logical implication:

P Q P=>Q
0 0 1
0 1 1
1 0 0
1 1 1

I put it to you that were you to draw up the truth table for the above
proposition (forall A and forall X), you would not have a logical
consistency i.e. you will have at least one false in the final column.
Ergo, "forall A. Option[A] implies A" is false. If you have all trues in
the final column, then everything I have just said has been disproven!

So why is it necessary to have "propositions that are false"? It is
known that anything to the contrary is equivalent to circumventing the
Turing halting problem, which is of course, not solved. In other words,
if we are to have a turing-complete system, we cannot escape the fact
that we must also use an inconsistent system of logic with the potential
for absurdity! This can often be very disappointing, but do not lament,
for we still have very good type systems that work within these
constraints -- in other words, there are still (very) practical
implications to explore further. This point is a very important one that
is missed by people who object in the way that the original article
does. Never mind too much about that.

As further reference, I strongly recommend exploring systems that are
*not* turing-complete (sacrifice) yet are total languages (benefit). In
other words, unlike Scala, they don't have any partial functions -- it's
simply not possible to write one! Examples that I am most familiar with
are Coq and Agda, but there are a few others too.

If you try to write Option.get in any of these (total) languages *your
code will simply not compile*. In the meantime, while we are using a
language with the properties of Scala, we enjoy the benefits of
turing-completeness (for whatever they might be for you) but at the
expense of the existence of partial functions. It's simply impractical
to object to the continued presence of these functions. They *must* exist.

Interesting reading on this topic/rant/excursion:
* Curry-Howard Isomorphism
* Turing's Halting Problem
* Free Theorems by Philip Wadler

I hope that helps mate. Let me know how you get on.

Egon Nijns wrote:
> Tony,
>
> Please elaborate on this. I'm not seeing the necessity.
>
> Kind regards,
> Egon.
>
> Tony Morris wrote:
>
> Sean,
> Scala *must* have unsafe methods. It's absolutely necessary. Nothing is
> solved by moving or removing the get function in this respect.
>
> Sean Leather wrote:
>
>> Thanks for the response. There are quite a few replies here, and I'm
>> certain I don't understand most. As a result, I will try to clarify my
>> question.
>>
>> Why does the method "get" exist in the Option class?
>>
>>
>> The point of this question is that the method "get" is by definition
>> unsafe. By unsafe, I mean that it will likely lead a programmer who
>> uses it into error. Why is it unsafe? Let's review the code:
>>
>>
>> sealed abstract class Option[+A] extends Product { def get: A }
>> final case class Some[+A](x: A) extends Option[A] { def get = x }
>> case object None extends Option[Nothing] { def get = throw new
>> NoSuchElementException("None.get") }
>>
>>
>> Since "get" is defined in the class Option, there is an implication
>> that each subclass will override it and return some A value. Looking
>> at each inheritor, we see that Some overrides and results in a value,
>> but None throws an exception. Since there are only two subclasses and
>> half of them are exceptional cases, I'd say it's pretty clear that
>> "get" will lead somebody into error. Thus, it is unsafe.
>>
>> For reasons of type safety, shouldn't "get" only exist in Some? Or
>> is this just another way of replacing "x.getOrElse(default)" with
>> "try { x.get } catch { default }"?
>>
>>
>> I'm suggesting that "get" not be defined in Option but rather in Some.
>> That provides one way to get the value out of Some. But how do you get
>> the value out of an Option? Again, I'm new to Scala but I already see
>> multiple ways:
>>
>> * getOrElse
>> * foreach/for
>> * iterator
>> * opt match { case Some(x) => ... ; case None => ... }
>>
>> And I'm sure there are others.
>>
>> Of course, this is not to say that a method equivalent to "get" can't
>> still be written outside of Option.
>>
>> def fromSome(opt: Option[A]) = opt match {
>> case Some(x) => x
>> case None => throw new NoSuchElementException("fromSome")
>> }
>>
>> However, by putting "Option.get" (and even "orNull" and possibly
>> others) in the standard library, it encourages programmers to use
>> unsafe methods by making it easy. I get the impression that such
>> unsafe methods are generally included in the Scala libraries. So, I
>> suppose my real question should be: Why are unsafe methods included in
>> the standard libraries?
>>
>> Regards,
>> Sean
>>
>
>

Russ P.
Joined: 2009-01-31,
User offline. Last seen 1 year 26 weeks ago.
Re: Re: Why have method "get" in Option?
The "Option" class is a great idea, but if it didn't exist, it's main functionality could be achieved simply with a List. An empty List would represent "None," and a List with a single element would represent "Some." A "for" or "foreach" loop would work exactly the same on it. Using "get" would be equivalent to indexing into the first (zeroth?) element, something you obviously shouldn't do unless you are sure it is not empty.

Russ P.
Erik Engbrecht
Joined: 2008-12-19,
User offline. Last seen 3 years 18 weeks ago.
Re: Re: Why have method "get" in Option?
That's crazy talk!  Next thing you know, someone will suggest that Nil is the same as false...  :-)

On Mon, Aug 16, 2010 at 6:29 AM, Russ Paielli <russ.paielli@gmail.com> wrote:
The "Option" class is a great idea, but if it didn't exist, it's main functionality could be achieved simply with a List. An empty List would represent "None," and a List with a single element would represent "Some." A "for" or "foreach" loop would work exactly the same on it. Using "get" would be equivalent to indexing into the first (zeroth?) element, something you obviously shouldn't do unless you are sure it is not empty.

Russ P.



--
http://erikengbrecht.blogspot.com/
Tony Morris 2
Joined: 2009-03-20,
User offline. Last seen 42 years 45 weeks ago.
Re: Re: Why have method "get" in Option?

This is not true.

Russ Paielli wrote:
> The "Option" class is a great idea, but if it didn't exist, it's main
> functionality could be achieved simply with a List. An empty List
> would represent "None," and a List with a single element would
> represent "Some." A "for" or "foreach" loop would work exactly the
> same on it. Using "get" would be equivalent to indexing into the first
> (zeroth?) element, something you obviously shouldn't do unless you are
> sure it is not empty.
>
> Russ P.

Chris Marshall
Joined: 2009-06-17,
User offline. Last seen 44 weeks 3 days ago.
RE: Re: Why have method "get" in Option?
But haven't you said before that Option is just a List with a maximum length of 1?

> Date: Mon, 16 Aug 2010 20:37:17 +1000
> From: tonymorris@gmail.com
>
> This is not true.
>
> Russ Paielli wrote:
> > The "Option" class is a great idea, but if it didn't exist, it's main
> > functionality could be achieved simply with a List. An empty List
> > would represent "None," and a List with a single element would
> > represent "Some."> >
> > Russ P.

Willis Blackburn
Joined: 2010-06-16,
User offline. Last seen 42 years 45 weeks ago.
Re: Re: Why have method "get" in Option?

Of course it is, and I was going to mention that for the same reasons you suggest removing get from Option, you might as well remove, for example, apply from Array, because the fact that it accepts an integer suggests that Array can return a value for any index, which will lead developers to fail to check indexes. Option is simply a List or Array with either zero members or one.

W

On Aug 16, 2010, at 6:37 AM, Tony Morris wrote:

> This is not true.
>
> Russ Paielli wrote:
>> The "Option" class is a great idea, but if it didn't exist, it's main
>> functionality could be achieved simply with a List. An empty List
>> would represent "None," and a List with a single element would
>> represent "Some." A "for" or "foreach" loop would work exactly the
>> same on it. Using "get" would be equivalent to indexing into the first
>> (zeroth?) element, something you obviously shouldn't do unless you are
>> sure it is not empty.
>>
>> Russ P.
>

ichoran
Joined: 2009-08-14,
User offline. Last seen 2 years 3 weeks ago.
Re: Re: Why have method "get" in Option?
On Mon, Aug 16, 2010 at 6:29 AM, Russ Paielli <russ.paielli@gmail.com> wrote:
The "Option" class is a great idea, but if it didn't exist, it's main functionality could be achieved simply with a List. An empty List would represent "None," and a List with a single element would represent "Some."

Um...


def ++[A](a: TraversableOnce[A]): List[A]

List(1) ++ List (2)
Some(1) ++ Some(2)  // ??


def flatMap[B](f: A => Traversable[B]): List[B]
def flatMap[B](f: A => Option[B]): Option[B]

List(2).flatMap(_ => Array("Hi","there"))
Some(2).flatMap(_ => Array("Hi","there"))  // ??


You could make do with using List instead of Option (if List had a headOrElse method), but errors with lists of greater than length 1 would likely be common.

  --Rex
 
Derek Williams
Joined: 2009-06-13,
User offline. Last seen 42 years 45 weeks ago.
Re: Re: Why have method "get" in Option?

I think Russ' point was more towards the fact that it is just as
unsafe to call list.head and list.tail as it is to call option.get.
Where would we draw the line if we removed option.get?

On Mon, Aug 16, 2010 at 6:48 AM, Rex Kerr wrote:
> On Mon, Aug 16, 2010 at 6:29 AM, Russ Paielli
> wrote:
>>
>> The "Option" class is a great idea, but if it didn't exist, it's main
>> functionality could be achieved simply with a List. An empty List would
>> represent "None," and a List with a single element would represent "Some."
>
> Um...
>
>
> def ++[A](a: TraversableOnce[A]): List[A]
>
> List(1) ++ List (2)
> Some(1) ++ Some(2)  // ??
>
>
> def flatMap[B](f: A => Traversable[B]): List[B]
> def flatMap[B](f: A => Option[B]): Option[B]
>
> List(2).flatMap(_ => Array("Hi","there"))
> Some(2).flatMap(_ => Array("Hi","there"))  // ??
>
>
> You could make do with using List instead of Option (if List had a
> headOrElse method), but errors with lists of greater than length 1 would
> likely be common.
>
>   --Rex
>

Egon Nijns
Joined: 2010-05-19,
User offline. Last seen 42 years 45 weeks ago.
RE: Re: Why have method "get" in Option?

Hello Tony,

What I, as a mere mortal, am taking away from all this is: in order for a language to be Turing-complete it needs to incorporate the concept of undefinedness. Is this correct?

I do see the link with 'get' being defined in Option, but it's still hard to understand/defend from an OO programmer's point of view.

I'm replying before fully understanding the details of your email, (it would not be polite to keep you waiting forever), but I'm always interested to keep learning, so thanks for the references and your time.

Kind regards,
Egon.

-----Oorspronkelijk bericht-----
Van: Tony Morris [mailto:tonymorris@gmail.com]
Verzonden: maandag 16 augustus 2010 11:12
Aan: Egon Nijns
CC: Sean Leather; Scala Users Lists
Onderwerp: Re: [scala-user] Re: Why have method "get" in Option?

Hello Egon,
The get method is alleged to be objectionable because it is a partial
function. Specifically, it is undefined for at least one element of its
domain (namely None). This idea of "undefinedness" is often denoted
several ways:
* undefined
* non-terminating computation
* bottom
* logical absurdity (more on this below)
* ⊥
*

Let's take a little excursion into the "logical absurdity" notation.
What does this mean? It means this...

The following proposition is false:

"Option[A] => A"

But what does this mean exactly? To say it out loud, "for all values A,
then Option[A] implies A is a false statement." The next question is,
but what exactly is Option? Well, it's a data type with two constructors
(None and Some), but it can also be represented this way:

trait Option[A] {
def fold[X](none: => X, some: A => X): X
}

In other words, the above trait is *exactly equivalent* to scala.Option.
I'm not going to show why in any detail, so please take my word for it
for now. Any function you can write with scala.Option I can write with
my.Option and vice versa -- they are isomorphic -- I did this by
exploiting the catamorphism for Option (note that passing None and Some
to fold gives you an identity function). This is a fun side-exercise if
you're keen; write the entire Option API using this one abstract method
fold -- I assure you it can be done, there is no trick.

So anyway, now we can safely change our proposition and we are still
saying the same thing:

forall A. (forall X. (X, A => X) => X) => A is a false statement.

You can observe the falsity of this proposition by drawing up a truth
table. Note that tupling is equivalent to logical conjunction (AND),
whose truth table I am sure you are familiar with. Here is the truth
table for logical implication:

P Q P=>Q
0 0 1
0 1 1
1 0 0
1 1 1

I put it to you that were you to draw up the truth table for the above
proposition (forall A and forall X), you would not have a logical
consistency i.e. you will have at least one false in the final column.
Ergo, "forall A. Option[A] implies A" is false. If you have all trues in
the final column, then everything I have just said has been disproven!

So why is it necessary to have "propositions that are false"? It is
known that anything to the contrary is equivalent to circumventing the
Turing halting problem, which is of course, not solved. In other words,
if we are to have a turing-complete system, we cannot escape the fact
that we must also use an inconsistent system of logic with the potential
for absurdity! This can often be very disappointing, but do not lament,
for we still have very good type systems that work within these
constraints -- in other words, there are still (very) practical
implications to explore further. This point is a very important one that
is missed by people who object in the way that the original article
does. Never mind too much about that.

As further reference, I strongly recommend exploring systems that are
*not* turing-complete (sacrifice) yet are total languages (benefit). In
other words, unlike Scala, they don't have any partial functions -- it's
simply not possible to write one! Examples that I am most familiar with
are Coq and Agda, but there are a few others too.

If you try to write Option.get in any of these (total) languages *your
code will simply not compile*. In the meantime, while we are using a
language with the properties of Scala, we enjoy the benefits of
turing-completeness (for whatever they might be for you) but at the
expense of the existence of partial functions. It's simply impractical
to object to the continued presence of these functions. They *must* exist.

Interesting reading on this topic/rant/excursion:
* Curry-Howard Isomorphism
* Turing's Halting Problem
* Free Theorems by Philip Wadler

I hope that helps mate. Let me know how you get on.

Egon Nijns wrote:
> Tony,
>
> Please elaborate on this. I'm not seeing the necessity.
>
> Kind regards,
> Egon.
>
> Tony Morris wrote:
>
> Sean,
> Scala *must* have unsafe methods. It's absolutely necessary. Nothing is
> solved by moving or removing the get function in this respect.
>
> Sean Leather wrote:
>
>> Thanks for the response. There are quite a few replies here, and I'm
>> certain I don't understand most. As a result, I will try to clarify my
>> question.
>>
>> Why does the method "get" exist in the Option class?
>>
>>
>> The point of this question is that the method "get" is by definition
>> unsafe. By unsafe, I mean that it will likely lead a programmer who
>> uses it into error. Why is it unsafe? Let's review the code:
>>
>>
>> sealed abstract class Option[+A] extends Product { def get: A }
>> final case class Some[+A](x: A) extends Option[A] { def get = x }
>> case object None extends Option[Nothing] { def get = throw new
>> NoSuchElementException("None.get") }
>>
>>
>> Since "get" is defined in the class Option, there is an implication
>> that each subclass will override it and return some A value. Looking
>> at each inheritor, we see that Some overrides and results in a value,
>> but None throws an exception. Since there are only two subclasses and
>> half of them are exceptional cases, I'd say it's pretty clear that
>> "get" will lead somebody into error. Thus, it is unsafe.
>>
>> For reasons of type safety, shouldn't "get" only exist in Some? Or
>> is this just another way of replacing "x.getOrElse(default)" with
>> "try { x.get } catch { default }"?
>>
>>
>> I'm suggesting that "get" not be defined in Option but rather in Some.
>> That provides one way to get the value out of Some. But how do you get
>> the value out of an Option? Again, I'm new to Scala but I already see
>> multiple ways:
>>
>> * getOrElse
>> * foreach/for
>> * iterator
>> * opt match { case Some(x) => ... ; case None => ... }
>>
>> And I'm sure there are others.
>>
>> Of course, this is not to say that a method equivalent to "get" can't
>> still be written outside of Option.
>>
>> def fromSome(opt: Option[A]) = opt match {
>> case Some(x) => x
>> case None => throw new NoSuchElementException("fromSome")
>> }
>>
>> However, by putting "Option.get" (and even "orNull" and possibly
>> others) in the standard library, it encourages programmers to use
>> unsafe methods by making it easy. I get the impression that such
>> unsafe methods are generally included in the Scala libraries. So, I
>> suppose my real question should be: Why are unsafe methods included in
>> the standard libraries?
>>
>> Regards,
>> Sean
>>
>
>

Russ P.
Joined: 2009-01-31,
User offline. Last seen 1 year 26 weeks ago.
Re: Re: Why have method "get" in Option?
A few weeks ago, I posted a question asking about how to get the value (if one exists) out of an "Option." (At the time, I didn't realize that Option is just a class that I could look up in the docs.) Several replies suggested that I use "for" or "foreach." At first I was a bit puzzled, but after thinking about it, I realized that this approach is identical to getting the value from a List that can have zero or one element. I am not claiming that "Option" is exactly equivalent to a such a List in every situation, but I find that to be a useful way to think about it. It's a good way to explain it to newbies.

Russ P.

On Mon, Aug 16, 2010 at 6:07 AM, Derek Williams <derek@nebvin.ca> wrote:
I think Russ' point was more towards the fact that it is just as
unsafe to call list.head and list.tail as it is to call option.get.
Where would we draw the line if we removed option.get?

On Mon, Aug 16, 2010 at 6:48 AM, Rex Kerr <ichoran@gmail.com> wrote:
> On Mon, Aug 16, 2010 at 6:29 AM, Russ Paielli <russ.paielli@gmail.com>
> wrote:
>>
>> The "Option" class is a great idea, but if it didn't exist, it's main
>> functionality could be achieved simply with a List. An empty List would
>> represent "None," and a List with a single element would represent "Some."
>
> Um...
>
>
> def ++[A](a: TraversableOnce[A]): List[A]
>
> List(1) ++ List (2)
> Some(1) ++ Some(2)  // ??
>
>
> def flatMap[B](f: A => Traversable[B]): List[B]
> def flatMap[B](f: A => Option[B]): Option[B]
>
> List(2).flatMap(_ => Array("Hi","there"))
> Some(2).flatMap(_ => Array("Hi","there"))  // ??
>
>
> You could make do with using List instead of Option (if List had a
> headOrElse method), but errors with lists of greater than length 1 would
> likely be common.
>
>   --Rex
>



--
Derek



--
http://RussP.us
Tony Morris 2
Joined: 2009-03-20,
User offline. Last seen 42 years 45 weeks ago.
Re: Re: Why have method "get" in Option?

Yes.

christopher marshall wrote:
> But haven't you said before that Option is just a List with a maximum
> length of 1?
>
> > Date: Mon, 16 Aug 2010 20:37:17 +1000
> > From: tonymorris@gmail.com
> >
> > This is not true.
> >
> > Russ Paielli wrote:
> > > The "Option" class is a great idea, but if it didn't exist, it's main
> > > functionality could be achieved simply with a List. An empty List
> > > would represent "None," and a List with a single element would
> > > represent "Some."
> > >
> > > Russ P.
>

Tony Morris 2
Joined: 2009-03-20,
User offline. Last seen 42 years 45 weeks ago.
Re: Re: Why have method "get" in Option?

You said "it's [sic] main functionality could be achieved simply with a
List."

What you probably really mean is that there is an injective from Option
to List but not a surjective function or perhaps that there is not an
arrow from Option to Identity*.

Whatever you mean, the "main functionality" of Option is most
emphatically not handled by List, or any other of the zillion other
types for which there is an injection. Those zillion other types would
be redundant if this were true.

It is true that explaining Option as "like a list but with the maximum
length of one" can be beneficial in teaching.

* case class Identity[A](a: A)

Russ Paielli wrote:
> A few weeks ago, I posted a question asking about how to get the value
> (if one exists) out of an "Option." (At the time, I didn't realize
> that Option is just a class that I could look up in the docs.) Several
> replies suggested that I use "for" or "foreach." At first I was a bit
> puzzled, but after thinking about it, I realized that this approach is
> identical to getting the value from a List that can have zero or one
> element. I am not claiming that "Option" is exactly equivalent to a
> such a List in every situation, but I find that to be a useful way to
> think about it. It's a good way to explain it to newbies.
>
> Russ P.
>
> On Mon, Aug 16, 2010 at 6:07 AM, Derek Williams > wrote:
>
> I think Russ' point was more towards the fact that it is just as
> unsafe to call list.head and list.tail as it is to call option.get.
> Where would we draw the line if we removed option.get?
>
> On Mon, Aug 16, 2010 at 6:48 AM, Rex Kerr > wrote:
> > On Mon, Aug 16, 2010 at 6:29 AM, Russ Paielli
> >
> > wrote:
> >>
> >> The "Option" class is a great idea, but if it didn't exist,
> it's main
> >> functionality could be achieved simply with a List. An empty
> List would
> >> represent "None," and a List with a single element would
> represent "Some."
> >
> > Um...
> >
> >
> > def ++[A](a: TraversableOnce[A]): List[A]
> >
> > List(1) ++ List (2)
> > Some(1) ++ Some(2) // ??
> >
> >
> > def flatMap[B](f: A => Traversable[B]): List[B]
> > def flatMap[B](f: A => Option[B]): Option[B]
> >
> > List(2).flatMap(_ => Array("Hi","there"))
> > Some(2).flatMap(_ => Array("Hi","there")) // ??
> >
> >
> > You could make do with using List instead of Option (if List had a
> > headOrElse method), but errors with lists of greater than length
> 1 would
> > likely be common.
> >
> > --Rex
> >
>
>
>
> --
> Derek
>
>
>
>

Russ P.
Joined: 2009-01-31,
User offline. Last seen 1 year 26 weeks ago.
Re: Re: Why have method "get" in Option?

On Mon, Aug 16, 2010 at 2:22 PM, Tony Morris <tonymorris@gmail.com> wrote:
You said "it's [sic] main functionality could be achieved simply with a
List."


Darnit ... I used "it's" when I should have used "its"! How embarrassing! I usually get that one right.
 
What you probably really mean is that there is an injective from Option
to List but not a surjective function or perhaps that there is not an
arrow from Option to Identity*.


I meant exactly what I wrote (except for the "it's"). Suppose Scala had no "Option" class, and I need to pass along a number if a valid one is available or some signal if one is not. Suppose, moreover, that I don't want to use null or in-band signaling (e.g., defining an otherwise valid number such as -99999 to represent an invalid number). What could I do? One alternative is to simply pass a List that is empty if a valid number is not available. The client would then simply use "for" or "foreach" and would not have to check for null or -99999. Depending on how it is used, the List could even contain more than one element. List may not be as elegant or as versatile as "Option" for this purpose, but it solves the basic problem.

 
Whatever you mean, the "main functionality" of Option is most
emphatically not handled by List, or any other of the zillion other
types for which there is an injection. Those zillion other types would
be redundant if this were true.


I didn't say that Option is handled by List. I just said that List (or Array or Set for that matter) could be used to achieve the same basic functionality.
 
It is true that explaining Option as "like a list but with the maximum
length of one" can be beneficial in teaching.


It sure helps simple-minded people like me.

Russ P.

--
http://RussP.us
Andrew Milkowski
Joined: 2010-07-26,
User offline. Last seen 42 years 45 weeks ago.
Re: Re: Why have method "get" in Option?

Tony, thanks again for using "sharp knife" , your blog entry

http://blog.tmorris.net/optional-a-negative-proof/

Is especially insightful, I liked your detailed breakdown of a statement below (comprehension?) Into truth table

forall a x. ((a -> x) -> x -> x) -> a

And hence impossibility of Optional a -> a (by functor isomorphism to the above, logical inconsistency found in one implies logical inconsistency in the other?)

its all starting to look more like a category theory:) never would think (but suspect) it would make it into a programming language like scala potentially used in the mainstream (outside haskell that never really ventured outside academia, and it should have long time ago, world would be much better of:)

So next I liked comment made by anonymous (best are always modest)

It is Haskell derivation of logical inconsistency, again looks like using functor isomorphism

http://blog.tmorris.net/optional-a-negative-proof/#comment-42134

By final conclusion in this comment:
"
That is, doesThisExist Optional is the same as Id b for any b :: B. This is impossible, therefore doesThisExist does’t exist."

Does author of the comment simply replaced Option a -> a with
Functor id and failure of functor isomoprhism proved that such statement can not form "closed algebra" and therefore it is not consistent? Or I completely missed the boat?:) in either case highly appreciate your further comments on the comment:)

Thanks much!

Sent from my Verizon Wireless BlackBerry

-----Original Message-----
From: Tony Morris
Date: Mon, 16 Aug 2010 19:12:00
To: Egon Nijns
Cc: Sean Leather; Scala Users Lists
Subject: Re: [scala-user] Re: Why have method "get" in Option?

Hello Egon,
The get method is alleged to be objectionable because it is a partial
function. Specifically, it is undefined for at least one element of its
domain (namely None). This idea of "undefinedness" is often denoted
several ways:
* undefined
* non-terminating computation
* bottom
* logical absurdity (more on this below)
* ⊥
*

Let's take a little excursion into the "logical absurdity" notation.
What does this mean? It means this...

The following proposition is false:

"Option[A] => A"

But what does this mean exactly? To say it out loud, "for all values A,
then Option[A] implies A is a false statement." The next question is,
but what exactly is Option? Well, it's a data type with two constructors
(None and Some), but it can also be represented this way:

trait Option[A] {
def fold[X](none: => X, some: A => X): X
}

In other words, the above trait is *exactly equivalent* to scala.Option.
I'm not going to show why in any detail, so please take my word for it
for now. Any function you can write with scala.Option I can write with
my.Option and vice versa -- they are isomorphic -- I did this by
exploiting the catamorphism for Option (note that passing None and Some
to fold gives you an identity function). This is a fun side-exercise if
you're keen; write the entire Option API using this one abstract method
fold -- I assure you it can be done, there is no trick.

So anyway, now we can safely change our proposition and we are still
saying the same thing:

forall A. (forall X. (X, A => X) => X) => A is a false statement.

You can observe the falsity of this proposition by drawing up a truth
table. Note that tupling is equivalent to logical conjunction (AND),
whose truth table I am sure you are familiar with. Here is the truth
table for logical implication:

P Q P=>Q
0 0 1
0 1 1
1 0 0
1 1 1

I put it to you that were you to draw up the truth table for the above
proposition (forall A and forall X), you would not have a logical
consistency i.e. you will have at least one false in the final column.
Ergo, "forall A. Option[A] implies A" is false. If you have all trues in
the final column, then everything I have just said has been disproven!

So why is it necessary to have "propositions that are false"? It is
known that anything to the contrary is equivalent to circumventing the
Turing halting problem, which is of course, not solved. In other words,
if we are to have a turing-complete system, we cannot escape the fact
that we must also use an inconsistent system of logic with the potential
for absurdity! This can often be very disappointing, but do not lament,
for we still have very good type systems that work within these
constraints -- in other words, there are still (very) practical
implications to explore further. This point is a very important one that
is missed by people who object in the way that the original article
does. Never mind too much about that.

As further reference, I strongly recommend exploring systems that are
*not* turing-complete (sacrifice) yet are total languages (benefit). In
other words, unlike Scala, they don't have any partial functions -- it's
simply not possible to write one! Examples that I am most familiar with
are Coq and Agda, but there are a few others too.

If you try to write Option.get in any of these (total) languages *your
code will simply not compile*. In the meantime, while we are using a
language with the properties of Scala, we enjoy the benefits of
turing-completeness (for whatever they might be for you) but at the
expense of the existence of partial functions. It's simply impractical
to object to the continued presence of these functions. They *must* exist.

Interesting reading on this topic/rant/excursion:
* Curry-Howard Isomorphism
* Turing's Halting Problem
* Free Theorems by Philip Wadler

I hope that helps mate. Let me know how you get on.

Egon Nijns wrote:
> Tony,
>
> Please elaborate on this. I'm not seeing the necessity.
>
> Kind regards,
> Egon.
>
> Tony Morris wrote:
>
> Sean,
> Scala *must* have unsafe methods. It's absolutely necessary. Nothing is
> solved by moving or removing the get function in this respect.
>
> Sean Leather wrote:
>
>> Thanks for the response. There are quite a few replies here, and I'm
>> certain I don't understand most. As a result, I will try to clarify my
>> question.
>>
>> Why does the method "get" exist in the Option class?
>>
>>
>> The point of this question is that the method "get" is by definition
>> unsafe. By unsafe, I mean that it will likely lead a programmer who
>> uses it into error. Why is it unsafe? Let's review the code:
>>
>>
>> sealed abstract class Option[+A] extends Product { def get: A }
>> final case class Some[+A](x: A) extends Option[A] { def get = x }
>> case object None extends Option[Nothing] { def get = throw new
>> NoSuchElementException("None.get") }
>>
>>
>> Since "get" is defined in the class Option, there is an implication
>> that each subclass will override it and return some A value. Looking
>> at each inheritor, we see that Some overrides and results in a value,
>> but None throws an exception. Since there are only two subclasses and
>> half of them are exceptional cases, I'd say it's pretty clear that
>> "get" will lead somebody into error. Thus, it is unsafe.
>>
>> For reasons of type safety, shouldn't "get" only exist in Some? Or
>> is this just another way of replacing "x.getOrElse(default)" with
>> "try { x.get } catch { default }"?
>>
>>
>> I'm suggesting that "get" not be defined in Option but rather in Some.
>> That provides one way to get the value out of Some. But how do you get
>> the value out of an Option? Again, I'm new to Scala but I already see
>> multiple ways:
>>
>> * getOrElse
>> * foreach/for
>> * iterator
>> * opt match { case Some(x) => ... ; case None => ... }
>>
>> And I'm sure there are others.
>>
>> Of course, this is not to say that a method equivalent to "get" can't
>> still be written outside of Option.
>>
>> def fromSome(opt: Option[A]) = opt match {
>> case Some(x) => x
>> case None => throw new NoSuchElementException("fromSome")
>> }
>>
>> However, by putting "Option.get" (and even "orNull" and possibly
>> others) in the standard library, it encourages programmers to use
>> unsafe methods by making it easy. I get the impression that such
>> unsafe methods are generally included in the Scala libraries. So, I
>> suppose my real question should be: Why are unsafe methods included in
>> the standard libraries?
>>
>> Regards,
>> Sean
>>
>
>

Derek Chen-Becker
Joined: 2008-12-16,
User offline. Last seen 42 years 45 weeks ago.
Re: Re: Why have method "get" in Option?

On Mon, Aug 16, 2010 at 06:29:15PM -0700, Russ Paielli wrote:
> Darnit ... I used "it's" when I should have used "its"! How embarrassing! I
> usually get that one right.

Totally off-topic, but it sounds like you need a visit from Bob the Angry
Flower:

http://www.angryflower.com/bobsqu.gif

Still makes me laugh after all these years...

Derek

Tony Morris 2
Joined: 2009-03-20,
User offline. Last seen 42 years 45 weeks ago.
Re: Re: Why have method "get" in Option?

Egon Nijns wrote:
> Hello Tony,
>
> What I, as a mere mortal, am taking away from all this is: in order for a language to be Turing-complete it needs to incorporate the concept of undefinedness. Is this correct?
>
That's exactly right, yes.
> I do see the link with 'get' being defined in Option, but it's still hard to understand/defend from an OO programmer's point of view.
>
I'm not sure what you mean here. OO-programmers are also susceptible to
this problem. However, I would also point out that programmers of
mainstream languages are *far more* susceptible to this problem.

It is certainly hard to defend from a total programmer's point of view :)
> I'm replying before fully understanding the details of your email, (it would not be polite to keep you waiting forever), but I'm always interested to keep learning, so thanks for the references and your time.
>
Yeah mate, no worries. Questions any time.

> Kind regards,
> Egon.
>
> -----Oorspronkelijk bericht-----
> Van: Tony Morris [mailto:tonymorris@gmail.com]
> Verzonden: maandag 16 augustus 2010 11:12
> Aan: Egon Nijns
> CC: Sean Leather; Scala Users Lists
> Onderwerp: Re: [scala-user] Re: Why have method "get" in Option?
>
> Hello Egon,
> The get method is alleged to be objectionable because it is a partial
> function. Specifically, it is undefined for at least one element of its
> domain (namely None). This idea of "undefinedness" is often denoted
> several ways:
> * undefined
> * non-terminating computation
> * bottom
> * logical absurdity (more on this below)
> * ⊥
> *
>
> Let's take a little excursion into the "logical absurdity" notation.
> What does this mean? It means this...
>
> The following proposition is false:
>
> "Option[A] => A"
>
> But what does this mean exactly? To say it out loud, "for all values A,
> then Option[A] implies A is a false statement." The next question is,
> but what exactly is Option? Well, it's a data type with two constructors
> (None and Some), but it can also be represented this way:
>
> trait Option[A] {
> def fold[X](none: => X, some: A => X): X
> }
>
> In other words, the above trait is *exactly equivalent* to scala.Option.
> I'm not going to show why in any detail, so please take my word for it
> for now. Any function you can write with scala.Option I can write with
> my.Option and vice versa -- they are isomorphic -- I did this by
> exploiting the catamorphism for Option (note that passing None and Some
> to fold gives you an identity function). This is a fun side-exercise if
> you're keen; write the entire Option API using this one abstract method
> fold -- I assure you it can be done, there is no trick.
>
> So anyway, now we can safely change our proposition and we are still
> saying the same thing:
>
> forall A. (forall X. (X, A => X) => X) => A is a false statement.
>
> You can observe the falsity of this proposition by drawing up a truth
> table. Note that tupling is equivalent to logical conjunction (AND),
> whose truth table I am sure you are familiar with. Here is the truth
> table for logical implication:
>
> P Q P=>Q
> 0 0 1
> 0 1 1
> 1 0 0
> 1 1 1
>
> I put it to you that were you to draw up the truth table for the above
> proposition (forall A and forall X), you would not have a logical
> consistency i.e. you will have at least one false in the final column.
> Ergo, "forall A. Option[A] implies A" is false. If you have all trues in
> the final column, then everything I have just said has been disproven!
>
> So why is it necessary to have "propositions that are false"? It is
> known that anything to the contrary is equivalent to circumventing the
> Turing halting problem, which is of course, not solved. In other words,
> if we are to have a turing-complete system, we cannot escape the fact
> that we must also use an inconsistent system of logic with the potential
> for absurdity! This can often be very disappointing, but do not lament,
> for we still have very good type systems that work within these
> constraints -- in other words, there are still (very) practical
> implications to explore further. This point is a very important one that
> is missed by people who object in the way that the original article
> does. Never mind too much about that.
>
> As further reference, I strongly recommend exploring systems that are
> *not* turing-complete (sacrifice) yet are total languages (benefit). In
> other words, unlike Scala, they don't have any partial functions -- it's
> simply not possible to write one! Examples that I am most familiar with
> are Coq and Agda, but there are a few others too.
>
> If you try to write Option.get in any of these (total) languages *your
> code will simply not compile*. In the meantime, while we are using a
> language with the properties of Scala, we enjoy the benefits of
> turing-completeness (for whatever they might be for you) but at the
> expense of the existence of partial functions. It's simply impractical
> to object to the continued presence of these functions. They *must* exist.
>
> Interesting reading on this topic/rant/excursion:
> * Curry-Howard Isomorphism
> * Turing's Halting Problem
> * Free Theorems by Philip Wadler
>
> I hope that helps mate. Let me know how you get on.
>
> Egon Nijns wrote:
>
>> Tony,
>>
>> Please elaborate on this. I'm not seeing the necessity.
>>
>> Kind regards,
>> Egon.
>>
>> Tony Morris wrote:
>>
>> Sean,
>> Scala *must* have unsafe methods. It's absolutely necessary. Nothing is
>> solved by moving or removing the get function in this respect.
>>
>> Sean Leather wrote:
>>
>>
>>> Thanks for the response. There are quite a few replies here, and I'm
>>> certain I don't understand most. As a result, I will try to clarify my
>>> question.
>>>
>>> Why does the method "get" exist in the Option class?
>>>
>>>
>>> The point of this question is that the method "get" is by definition
>>> unsafe. By unsafe, I mean that it will likely lead a programmer who
>>> uses it into error. Why is it unsafe? Let's review the code:
>>>
>>>
>>> sealed abstract class Option[+A] extends Product { def get: A }
>>> final case class Some[+A](x: A) extends Option[A] { def get = x }
>>> case object None extends Option[Nothing] { def get = throw new
>>> NoSuchElementException("None.get") }
>>>
>>>
>>> Since "get" is defined in the class Option, there is an implication
>>> that each subclass will override it and return some A value. Looking
>>> at each inheritor, we see that Some overrides and results in a value,
>>> but None throws an exception. Since there are only two subclasses and
>>> half of them are exceptional cases, I'd say it's pretty clear that
>>> "get" will lead somebody into error. Thus, it is unsafe.
>>>
>>> For reasons of type safety, shouldn't "get" only exist in Some? Or
>>> is this just another way of replacing "x.getOrElse(default)" with
>>> "try { x.get } catch { default }"?
>>>
>>>
>>> I'm suggesting that "get" not be defined in Option but rather in Some.
>>> That provides one way to get the value out of Some. But how do you get
>>> the value out of an Option? Again, I'm new to Scala but I already see
>>> multiple ways:
>>>
>>> * getOrElse
>>> * foreach/for
>>> * iterator
>>> * opt match { case Some(x) => ... ; case None => ... }
>>>
>>> And I'm sure there are others.
>>>
>>> Of course, this is not to say that a method equivalent to "get" can't
>>> still be written outside of Option.
>>>
>>> def fromSome(opt: Option[A]) = opt match {
>>> case Some(x) => x
>>> case None => throw new NoSuchElementException("fromSome")
>>> }
>>>
>>> However, by putting "Option.get" (and even "orNull" and possibly
>>> others) in the standard library, it encourages programmers to use
>>> unsafe methods by making it easy. I get the impression that such
>>> unsafe methods are generally included in the Scala libraries. So, I
>>> suppose my real question should be: Why are unsafe methods included in
>>> the standard libraries?
>>>
>>> Regards,
>>> Sean
>>>
>>>
>>
>>
>
>

Naftoli Gugenheim
Joined: 2008-12-17,
User offline. Last seen 42 years 45 weeks ago.
Re: Re: Why have method "get" in Option?
Okay, but isn't it better to have 9 unsafe methods than 10 unsafe methods?

On Fri, Aug 13, 2010 at 10:38 PM, Tony Morris <tonymorris@gmail.com> wrote:
Sean,
Scala *must* have unsafe methods. It's absolutely necessary. Nothing is
solved by moving or removing the get function in this respect.

Sean Leather wrote:
> Thanks for the response. There are quite a few replies here, and I'm
> certain I don't understand most. As a result, I will try to clarify my
> question.
>
>     Why does the method "get" exist in the Option class?
>
>
> The point of this question is that the method "get" is by definition
> unsafe. By unsafe, I mean that it will likely lead a programmer who
> uses it into error. Why is it unsafe? Let's review the code:
>
>
>     sealed abstract class Option[+A] extends Product { def get: A }
>     final case class Some[+A](x: A) extends Option[A] { def get = x }
>     case object None extends Option[Nothing] { def get = throw new
>     NoSuchElementException("None.get") }
>
>
> Since "get" is defined in the class Option, there is an implication
> that each subclass will override it and return some A value. Looking
> at each inheritor, we see that Some overrides and results in a value,
> but None throws an exception. Since there are only two subclasses and
> half of them are exceptional cases, I'd say it's pretty clear that
> "get" will lead somebody into error. Thus, it is unsafe.
>
>     For reasons of type safety, shouldn't "get" only exist in Some? Or
>     is this just another way of replacing "x.getOrElse(default)" with
>     "try { x.get } catch { default }"?
>
>
> I'm suggesting that "get" not be defined in Option but rather in Some.
> That provides one way to get the value out of Some. But how do you get
> the value out of an Option? Again, I'm new to Scala but I already see
> multiple ways:
>
>     * getOrElse
>     * foreach/for
>     * iterator
>     * opt match { case Some(x) => ... ; case None => ... }
>
> And I'm sure there are others.
>
> Of course, this is not to say that a method equivalent to "get" can't
> still be written outside of Option.
>
> def fromSome(opt: Option[A]) = opt match {
>   case Some(x) => x
>   case None => throw new NoSuchElementException("fromSome")
> }
>
> However, by putting "Option.get" (and even "orNull" and possibly
> others) in the standard library, it encourages programmers to use
> unsafe methods by making it easy. I get the impression that such
> unsafe methods are generally included in the Scala libraries. So, I
> suppose my real question should be: Why are unsafe methods included in
> the standard libraries?
>
> Regards,
> Sean

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



Danielk
Joined: 2009-06-08,
User offline. Last seen 3 years 21 weeks ago.
Re: Re: Why have method "get" in Option?
But it is rather common that you want assume that the Option is in fact a Some - otherwise something has gone wrong outside of the control of the current code and we should fail with an exception. And it would be silly if you had to express this with a pattern match each time, or if every project had to implement its own utility function.

I would prefer if the method was called getUnsafe or something like that to gently dissuade people from using it without thinking first, but that is obviously just a matter of personal opinion.


On Tue, Aug 17, 2010 at 9:28 PM, Naftoli Gugenheim <naftoligug@gmail.com> wrote:
Okay, but isn't it better to have 9 unsafe methods than 10 unsafe methods?

On Fri, Aug 13, 2010 at 10:38 PM, Tony Morris <tonymorris@gmail.com> wrote:
Sean,
Scala *must* have unsafe methods. It's absolutely necessary. Nothing is
solved by moving or removing the get function in this respect.

Sean Leather wrote:
> Thanks for the response. There are quite a few replies here, and I'm
> certain I don't understand most. As a result, I will try to clarify my
> question.
>
>     Why does the method "get" exist in the Option class?
>
>
> The point of this question is that the method "get" is by definition
> unsafe. By unsafe, I mean that it will likely lead a programmer who
> uses it into error. Why is it unsafe? Let's review the code:
>
>
>     sealed abstract class Option[+A] extends Product { def get: A }
>     final case class Some[+A](x: A) extends Option[A] { def get = x }
>     case object None extends Option[Nothing] { def get = throw new
>     NoSuchElementException("None.get") }
>
>
> Since "get" is defined in the class Option, there is an implication
> that each subclass will override it and return some A value. Looking
> at each inheritor, we see that Some overrides and results in a value,
> but None throws an exception. Since there are only two subclasses and
> half of them are exceptional cases, I'd say it's pretty clear that
> "get" will lead somebody into error. Thus, it is unsafe.
>
>     For reasons of type safety, shouldn't "get" only exist in Some? Or
>     is this just another way of replacing "x.getOrElse(default)" with
>     "try { x.get } catch { default }"?
>
>
> I'm suggesting that "get" not be defined in Option but rather in Some.
> That provides one way to get the value out of Some. But how do you get
> the value out of an Option? Again, I'm new to Scala but I already see
> multiple ways:
>
>     * getOrElse
>     * foreach/for
>     * iterator
>     * opt match { case Some(x) => ... ; case None => ... }
>
> And I'm sure there are others.
>
> Of course, this is not to say that a method equivalent to "get" can't
> still be written outside of Option.
>
> def fromSome(opt: Option[A]) = opt match {
>   case Some(x) => x
>   case None => throw new NoSuchElementException("fromSome")
> }
>
> However, by putting "Option.get" (and even "orNull" and possibly
> others) in the standard library, it encourages programmers to use
> unsafe methods by making it easy. I get the impression that such
> unsafe methods are generally included in the Scala libraries. So, I
> suppose my real question should be: Why are unsafe methods included in
> the standard libraries?
>
> Regards,
> Sean

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




Russ P.
Joined: 2009-01-31,
User offline. Last seen 1 year 26 weeks ago.
Re: Re: Why have method "get" in Option?
On Tue, Aug 17, 2010 at 12:52 PM, Daniel Kristensen <daniel.kristensen@gmail.com> wrote:
But it is rather common that you want assume that the Option is in fact a Some - otherwise something has gone wrong outside of the control of the current code and we should fail with an exception. And it would be silly if you had to express this with a pattern match each time, or if every project had to implement its own utility function.

I would prefer if the method was called getUnsafe or something like that to gently dissuade people from using it without thinking first, but that is obviously just a matter of personal opinion.

I like that idea. How about "uncheckedGet" or just "unchecked"? That makes it clear what you are doing.

Russ P.

--
http://RussP.us
Sean Corfield
Joined: 2009-10-25,
User offline. Last seen 2 years 9 weeks ago.
Re: Re: Why have method "get" in Option?

On Tue, Aug 17, 2010 at 1:26 PM, Russ Paielli wrote:
> I like that idea. How about "uncheckedGet" or just "unchecked"? That makes
> it clear what you are doing.

Since we have getOrElse(), perhaps it should be getOrThrow() or getOrFail() :)

nilskp
Joined: 2009-01-30,
User offline. Last seen 1 year 27 weeks ago.
Re: Re: Why have method "get" in Option?
On Tue, Aug 17, 2010 at 5:22 PM, Sean Corfield <seancorfield@gmail.com> wrote:
On Tue, Aug 17, 2010 at 1:26 PM, Russ Paielli <russ.paielli@gmail.com> wrote:
> I like that idea. How about "uncheckedGet" or just "unchecked"? That makes
> it clear what you are doing.

Since we have getOrElse(), perhaps it should be getOrThrow() or getOrFail() :)

Please stop.

Naftoli Gugenheim
Joined: 2008-12-17,
User offline. Last seen 42 years 45 weeks ago.
Re: Re: Why have method "get" in Option?
In Lift your preference is implemented. Box's equivalent of get is called open_!. The _! is often appended to method names to mean "use with caution."

On Tue, Aug 17, 2010 at 3:52 PM, Daniel Kristensen <daniel.kristensen@gmail.com> wrote:
But it is rather common that you want assume that the Option is in fact a Some - otherwise something has gone wrong outside of the control of the current code and we should fail with an exception. And it would be silly if you had to express this with a pattern match each time, or if every project had to implement its own utility function.

I would prefer if the method was called getUnsafe or something like that to gently dissuade people from using it without thinking first, but that is obviously just a matter of personal opinion.


On Tue, Aug 17, 2010 at 9:28 PM, Naftoli Gugenheim <naftoligug@gmail.com> wrote:
Okay, but isn't it better to have 9 unsafe methods than 10 unsafe methods?

On Fri, Aug 13, 2010 at 10:38 PM, Tony Morris <tonymorris@gmail.com> wrote:
Sean,
Scala *must* have unsafe methods. It's absolutely necessary. Nothing is
solved by moving or removing the get function in this respect.

Sean Leather wrote:
> Thanks for the response. There are quite a few replies here, and I'm
> certain I don't understand most. As a result, I will try to clarify my
> question.
>
>     Why does the method "get" exist in the Option class?
>
>
> The point of this question is that the method "get" is by definition
> unsafe. By unsafe, I mean that it will likely lead a programmer who
> uses it into error. Why is it unsafe? Let's review the code:
>
>
>     sealed abstract class Option[+A] extends Product { def get: A }
>     final case class Some[+A](x: A) extends Option[A] { def get = x }
>     case object None extends Option[Nothing] { def get = throw new
>     NoSuchElementException("None.get") }
>
>
> Since "get" is defined in the class Option, there is an implication
> that each subclass will override it and return some A value. Looking
> at each inheritor, we see that Some overrides and results in a value,
> but None throws an exception. Since there are only two subclasses and
> half of them are exceptional cases, I'd say it's pretty clear that
> "get" will lead somebody into error. Thus, it is unsafe.
>
>     For reasons of type safety, shouldn't "get" only exist in Some? Or
>     is this just another way of replacing "x.getOrElse(default)" with
>     "try { x.get } catch { default }"?
>
>
> I'm suggesting that "get" not be defined in Option but rather in Some.
> That provides one way to get the value out of Some. But how do you get
> the value out of an Option? Again, I'm new to Scala but I already see
> multiple ways:
>
>     * getOrElse
>     * foreach/for
>     * iterator
>     * opt match { case Some(x) => ... ; case None => ... }
>
> And I'm sure there are others.
>
> Of course, this is not to say that a method equivalent to "get" can't
> still be written outside of Option.
>
> def fromSome(opt: Option[A]) = opt match {
>   case Some(x) => x
>   case None => throw new NoSuchElementException("fromSome")
> }
>
> However, by putting "Option.get" (and even "orNull" and possibly
> others) in the standard library, it encourages programmers to use
> unsafe methods by making it easy. I get the impression that such
> unsafe methods are generally included in the Scala libraries. So, I
> suppose my real question should be: Why are unsafe methods included in
> the standard libraries?
>
> Regards,
> Sean

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





Kevin Wright 2
Joined: 2010-05-30,
User offline. Last seen 26 weeks 4 days ago.
Re: Re: Why have method "get" in Option?
Which looks bit like `xml_http_request?` and suchlike in Ruby on RailsExcept... we're doing it in a language where the humble underscore is *already* heavily overloaded
Is it the naming pattern that should be used with caution, or the method?



On 17 August 2010 23:47, Naftoli Gugenheim <naftoligug@gmail.com> wrote:
In Lift your preference is implemented. Box's equivalent of get is called open_!. The _! is often appended to method names to mean "use with caution."

On Tue, Aug 17, 2010 at 3:52 PM, Daniel Kristensen <daniel.kristensen@gmail.com> wrote:
But it is rather common that you want assume that the Option is in fact a Some - otherwise something has gone wrong outside of the control of the current code and we should fail with an exception. And it would be silly if you had to express this with a pattern match each time, or if every project had to implement its own utility function.

I would prefer if the method was called getUnsafe or something like that to gently dissuade people from using it without thinking first, but that is obviously just a matter of personal opinion.


On Tue, Aug 17, 2010 at 9:28 PM, Naftoli Gugenheim <naftoligug@gmail.com> wrote:
Okay, but isn't it better to have 9 unsafe methods than 10 unsafe methods?

On Fri, Aug 13, 2010 at 10:38 PM, Tony Morris <tonymorris@gmail.com> wrote:
Sean,
Scala *must* have unsafe methods. It's absolutely necessary. Nothing is
solved by moving or removing the get function in this respect.

Sean Leather wrote:
> Thanks for the response. There are quite a few replies here, and I'm
> certain I don't understand most. As a result, I will try to clarify my
> question.
>
>     Why does the method "get" exist in the Option class?
>
>
> The point of this question is that the method "get" is by definition
> unsafe. By unsafe, I mean that it will likely lead a programmer who
> uses it into error. Why is it unsafe? Let's review the code:
>
>
>     sealed abstract class Option[+A] extends Product { def get: A }
>     final case class Some[+A](x: A) extends Option[A] { def get = x }
>     case object None extends Option[Nothing] { def get = throw new
>     NoSuchElementException("None.get") }
>
>
> Since "get" is defined in the class Option, there is an implication
> that each subclass will override it and return some A value. Looking
> at each inheritor, we see that Some overrides and results in a value,
> but None throws an exception. Since there are only two subclasses and
> half of them are exceptional cases, I'd say it's pretty clear that
> "get" will lead somebody into error. Thus, it is unsafe.
>
>     For reasons of type safety, shouldn't "get" only exist in Some? Or
>     is this just another way of replacing "x.getOrElse(default)" with
>     "try { x.get } catch { default }"?
>
>
> I'm suggesting that "get" not be defined in Option but rather in Some.
> That provides one way to get the value out of Some. But how do you get
> the value out of an Option? Again, I'm new to Scala but I already see
> multiple ways:
>
>     * getOrElse
>     * foreach/for
>     * iterator
>     * opt match { case Some(x) => ... ; case None => ... }
>
> And I'm sure there are others.
>
> Of course, this is not to say that a method equivalent to "get" can't
> still be written outside of Option.
>
> def fromSome(opt: Option[A]) = opt match {
>   case Some(x) => x
>   case None => throw new NoSuchElementException("fromSome")
> }
>
> However, by putting "Option.get" (and even "orNull" and possibly
> others) in the standard library, it encourages programmers to use
> unsafe methods by making it easy. I get the impression that such
> unsafe methods are generally included in the Scala libraries. So, I
> suppose my real question should be: Why are unsafe methods included in
> the standard libraries?
>
> Regards,
> Sean

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








--
Kevin Wright

mail/google talk: kev.lee.wright@gmail.com
wave: kev.lee.wright@googlewave.com
skype: kev.lee.wright
twitter: @thecoda

Tony Morris 2
Joined: 2009-03-20,
User offline. Last seen 42 years 45 weeks ago.
Re: Re: Why have method "get" in Option?

No.

Naftoli Gugenheim wrote:
> Okay, but isn't it better to have 9 unsafe methods than 10 unsafe
> methods?
>
>
> On Fri, Aug 13, 2010 at 10:38 PM, Tony Morris > wrote:
>
> Sean,
> Scala *must* have unsafe methods. It's absolutely necessary.
> Nothing is
> solved by moving or removing the get function in this respect.
>
> Sean Leather wrote:
> > Thanks for the response. There are quite a few replies here, and I'm
> > certain I don't understand most. As a result, I will try to
> clarify my
> > question.
> >
> > Why does the method "get" exist in the Option class?
> >
> >
> > The point of this question is that the method "get" is by definition
> > unsafe. By unsafe, I mean that it will likely lead a programmer who
> > uses it into error. Why is it unsafe? Let's review the code:
> >
> >
> > sealed abstract class Option[+A] extends Product { def get: A }
> > final case class Some[+A](x: A) extends Option[A] { def get
> = x }
> > case object None extends Option[Nothing] { def get = throw new
> > NoSuchElementException("None.get") }
> >
> >
> > Since "get" is defined in the class Option, there is an implication
> > that each subclass will override it and return some A value. Looking
> > at each inheritor, we see that Some overrides and results in a
> value,
> > but None throws an exception. Since there are only two
> subclasses and
> > half of them are exceptional cases, I'd say it's pretty clear that
> > "get" will lead somebody into error. Thus, it is unsafe.
> >
> > For reasons of type safety, shouldn't "get" only exist in
> Some? Or
> > is this just another way of replacing "x.getOrElse(default)"
> with
> > "try { x.get } catch { default }"?
> >
> >
> > I'm suggesting that "get" not be defined in Option but rather in
> Some.
> > That provides one way to get the value out of Some. But how do
> you get
> > the value out of an Option? Again, I'm new to Scala but I
> already see
> > multiple ways:
> >
> > * getOrElse
> > * foreach/for
> > * iterator
> > * opt match { case Some(x) => ... ; case None => ... }
> >
> > And I'm sure there are others.
> >
> > Of course, this is not to say that a method equivalent to "get"
> can't
> > still be written outside of Option.
> >
> > def fromSome(opt: Option[A]) = opt match {
> > case Some(x) => x
> > case None => throw new NoSuchElementException("fromSome")
> > }
> >
> > However, by putting "Option.get" (and even "orNull" and possibly
> > others) in the standard library, it encourages programmers to use
> > unsafe methods by making it easy. I get the impression that such
> > unsafe methods are generally included in the Scala libraries. So, I
> > suppose my real question should be: Why are unsafe methods
> included in
> > the standard libraries?
> >
> > Regards,
> > Sean
>
> --
> Tony Morris
> http://tmorris.net/
>
>
>

Naftoli Gugenheim
Joined: 2008-12-17,
User offline. Last seen 42 years 45 weeks ago.
Re: Re: Why have method "get" in Option?
Hmm... Is 0 unsafe methods better?
Meaning, do you say "no" because of some all-or-nothing principle; or because it's pointless to eliminate unsafe methods in a language that's turing complete and therefore not inherently safe anyway?
Also, when you "no" to the question "isn't it better..." do you mean that it's not better in any way at all, or that any way that it might be better is insignificant (relatively or absolutely)?

On Wed, Aug 18, 2010 at 4:54 AM, Tony Morris <tonymorris@gmail.com> wrote:
No.

Naftoli Gugenheim wrote:
> Okay, but isn't it better to have 9 unsafe methods than 10 unsafe
> methods?
>
>
> On Fri, Aug 13, 2010 at 10:38 PM, Tony Morris <tonymorris@gmail.com
> <mailto:tonymorris@gmail.com>> wrote:
>
>     Sean,
>     Scala *must* have unsafe methods. It's absolutely necessary.
>     Nothing is
>     solved by moving or removing the get function in this respect.
>
>     Sean Leather wrote:
>     > Thanks for the response. There are quite a few replies here, and I'm
>     > certain I don't understand most. As a result, I will try to
>     clarify my
>     > question.
>     >
>     >     Why does the method "get" exist in the Option class?
>     >
>     >
>     > The point of this question is that the method "get" is by definition
>     > unsafe. By unsafe, I mean that it will likely lead a programmer who
>     > uses it into error. Why is it unsafe? Let's review the code:
>     >
>     >
>     >     sealed abstract class Option[+A] extends Product { def get: A }
>     >     final case class Some[+A](x: A) extends Option[A] { def get
>     = x }
>     >     case object None extends Option[Nothing] { def get = throw new
>     >     NoSuchElementException("None.get") }
>     >
>     >
>     > Since "get" is defined in the class Option, there is an implication
>     > that each subclass will override it and return some A value. Looking
>     > at each inheritor, we see that Some overrides and results in a
>     value,
>     > but None throws an exception. Since there are only two
>     subclasses and
>     > half of them are exceptional cases, I'd say it's pretty clear that
>     > "get" will lead somebody into error. Thus, it is unsafe.
>     >
>     >     For reasons of type safety, shouldn't "get" only exist in
>     Some? Or
>     >     is this just another way of replacing "x.getOrElse(default)"
>     with
>     >     "try { x.get } catch { default }"?
>     >
>     >
>     > I'm suggesting that "get" not be defined in Option but rather in
>     Some.
>     > That provides one way to get the value out of Some. But how do
>     you get
>     > the value out of an Option? Again, I'm new to Scala but I
>     already see
>     > multiple ways:
>     >
>     >     * getOrElse
>     >     * foreach/for
>     >     * iterator
>     >     * opt match { case Some(x) => ... ; case None => ... }
>     >
>     > And I'm sure there are others.
>     >
>     > Of course, this is not to say that a method equivalent to "get"
>     can't
>     > still be written outside of Option.
>     >
>     > def fromSome(opt: Option[A]) = opt match {
>     >   case Some(x) => x
>     >   case None => throw new NoSuchElementException("fromSome")
>     > }
>     >
>     > However, by putting "Option.get" (and even "orNull" and possibly
>     > others) in the standard library, it encourages programmers to use
>     > unsafe methods by making it easy. I get the impression that such
>     > unsafe methods are generally included in the Scala libraries. So, I
>     > suppose my real question should be: Why are unsafe methods
>     included in
>     > the standard libraries?
>     >
>     > Regards,
>     > Sean
>
>     --
>     Tony Morris
>     http://tmorris.net/
>
>
>


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



Dmitry Grigoriev
Joined: 2009-07-12,
User offline. Last seen 42 years 45 weeks ago.
Re: Why have method "get" in Option?

On 08/13/2010 05:06 PM, Nils Kilden-Pedersen wrote:
> In the cases I use 'get' without checking I *want* a runtime error. It
> means I made a wrong assumption in my code and it better fail fast.
>

100% agreed. I also use Option.get as a shortcut for:
{assert(!Option.isEmpty); Option.get}

For example, when handling web form submissions, I found myself doing
field non-emptiness validation on javascript side with user-friendly
error messages, but just Option.get parameter values on server side. So
I wrap whole server-side form processing into single try-catch which
responds with "please enable javascript".

Russ P.
Joined: 2009-01-31,
User offline. Last seen 1 year 26 weeks ago.
Re: Re: Why have method "get" in Option?
On Mon, Aug 16, 2010 at 4:58 AM, Willis Blackburn <wboyce@panix.com> wrote:
Of course it is, and I was going to mention that for the same reasons you suggest removing get from Option, you might as well remove, for example, apply from Array, because the fact that it accepts an integer suggests that Array can return a value for any index, which will lead developers to fail to check indexes.  Option is simply a List or Array with either zero members or one.

W


> This is not true.
>
> Russ Paielli wrote:
>> The "Option" class is a great idea, but if it didn't exist, it's main
>> functionality could be achieved simply with a List. An empty List
>> would represent "None," and a List with a single element would
>> represent "Some." A "for" or "foreach" loop would work exactly the
>> same on it. Using "get" would be equivalent to indexing into the first
>> (zeroth?) element, something you obviously shouldn't do unless you are
>> sure it is not empty.
>>
>> Russ P.


I am having an interesting little private debate on this topic, and I'd be interested in knowing what others here think about it. Now, I realize that posting private email messages is unethical if personal information is exposed, but I figure it is ethical as long as no personal information or personal discussion is shown.

Actually, it is not so much a debate as a series of assertions by the person I am corresponding with. Here is a typical example of one of this person's replies to me:

<start of message>

"List (or Array or Set for that matter) could be used to achieve the
same basic functionality [as Option]."

This is outright false. One can only guess why you think it is true,
because it is complete nonsense. Does this make sense yet?

<end of message>

That's the entire message, and it is just one off several similar messages. He or she simply asserts that I am wrong and gives no reason or explanation whatsoever. Zero, zip, nada. At the same time, he/she ignores my explanation for my claim, then says he can only "guess" why I make it.

Now, it is entirely possible, I suppose, that I *am* wrong, but if I am, I'd like to know why. Any comments?

Russ P.

--
http://RussP.us
Erik Engbrecht
Joined: 2008-12-19,
User offline. Last seen 3 years 18 weeks ago.
Re: Re: Why have method "get" in Option?
I think it depends on your definition of "wrong."
From a contract/interface perspective List/Set/Array/etc convey something different than Option.  Option means zero to one, while the collections all mean zero to many.  So by using a generic collection for Option you introduce a situation similar to null, only instead of never knowing if you don't have an object without explicitly checking, you never know if you have more than one.
But I have a feeling the reasons that the person in question has are far more opaque to those without that person's knowledge, and far more obvious to those with it.
I'm pretty sure I understand what you mean and I don't personally think it is wrong.  Common Lisp gets along fine using nil for null/None, an empty list, and false.
On Fri, Aug 20, 2010 at 3:15 PM, Russ Paielli <russ.paielli@gmail.com> wrote:
On Mon, Aug 16, 2010 at 4:58 AM, Willis Blackburn <wboyce@panix.com> wrote:
Of course it is, and I was going to mention that for the same reasons you suggest removing get from Option, you might as well remove, for example, apply from Array, because the fact that it accepts an integer suggests that Array can return a value for any index, which will lead developers to fail to check indexes.  Option is simply a List or Array with either zero members or one.

W


> This is not true.
>
> Russ Paielli wrote:
>> The "Option" class is a great idea, but if it didn't exist, it's main
>> functionality could be achieved simply with a List. An empty List
>> would represent "None," and a List with a single element would
>> represent "Some." A "for" or "foreach" loop would work exactly the
>> same on it. Using "get" would be equivalent to indexing into the first
>> (zeroth?) element, something you obviously shouldn't do unless you are
>> sure it is not empty.
>>
>> Russ P.


I am having an interesting little private debate on this topic, and I'd be interested in knowing what others here think about it. Now, I realize that posting private email messages is unethical if personal information is exposed, but I figure it is ethical as long as no personal information or personal discussion is shown.

Actually, it is not so much a debate as a series of assertions by the person I am corresponding with. Here is a typical example of one of this person's replies to me:

<start of message>

"List (or Array or Set for that matter) could be used to achieve the
same basic functionality [as Option]."

This is outright false. One can only guess why you think it is true,
because it is complete nonsense. Does this make sense yet?

<end of message>

That's the entire message, and it is just one off several similar messages. He or she simply asserts that I am wrong and gives no reason or explanation whatsoever. Zero, zip, nada. At the same time, he/she ignores my explanation for my claim, then says he can only "guess" why I make it.

Now, it is entirely possible, I suppose, that I *am* wrong, but if I am, I'd like to know why. Any comments?

Russ P.

--
http://RussP.us



--
http://erikengbrecht.blogspot.com/
extempore
Joined: 2008-12-17,
User offline. Last seen 35 weeks 3 days ago.
Re: Re: Why have method "get" in Option?

On Fri, Aug 20, 2010 at 12:15:37PM -0700, Russ Paielli wrote:
> I am having an interesting little private debate on this topic, and
> I'd be interested in knowing what others here think about it. Now, I
> realize that posting private email messages is unethical if personal
> information is exposed, but I figure it is ethical as long as no
> personal information or personal discussion is shown.

If you were in charge of a police lineup there'd be five cops in uniform
and one guy in prisoner uniform and handcuffs. "Everything by the book
on this one, fellows! And... justice is served."

[If this is too opaque, not only would I have known who the person in
question was after the excerpts, I knew based solely on your first
sentence. Not that it makes any difference, but let's not take too much
credit for virtuousness. Wikileaks you ain't.]

Chris Marshall
Joined: 2009-06-17,
User offline. Last seen 44 weeks 3 days ago.
RE: Re: Why have method "get" in Option?
> To: scala-user@listes.epfl.ch
> From: mail@dimgel.ru
>
> On 08/13/2010 05:06 PM, Nils Kilden-Pedersen wrote:
> > In the cases I use 'get' without checking I *want* a runtime error. It
> > means I made a wrong assumption in my code and it better fail fast.

Um, wouldn't you prefer that the *compiler* might tell you that your code has a bug in it?

> 100% agreed. I also use Option.get as a shortcut for:> {assert(!Option.isEmpty); Option.get}

I am managing to completely avoid using Option.get - I must be doing it wrong! 
Danielk
Joined: 2009-06-08,
User offline. Last seen 3 years 21 weeks ago.
Re: Re: Why have method "get" in Option?
On Sun, Aug 22, 2010 at 10:22 PM, christopher marshall <oxbow_lakes@hotmail.com> wrote:
> To: scala-user@listes.epfl.ch
> From: mail@dimgel.ru
>
> On 08/13/2010 05:06 PM, Nils Kilden-Pedersen wrote:
> > In the cases I use 'get' without checking I *want* a runtime error. It
> > means I made a wrong assumption in my code and it better fail fast.

Um, wouldn't you prefer that the *compiler* might tell you that your code has a bug in it?

It would be awesome! Note though that the bug in this case is typically in some other part of the program. So while it would be great if static analysis could flag this, most often it can't in practice.
 

> 100% agreed. I also use Option.get as a shortcut for: > {assert(!Option.isEmpty); Option.get}

I am managing to completely avoid using Option.get - I must be doing it wrong! 

I don't think anyone is claiming it is hard to avoid using Option.get. The problem is that for some usecases you'll just end up rolling your own - either as a utility method or inline at each use site.

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