Possible candidate for addition to the Option API?

36 views
Skip to first unread message

Ken McDonald

unread,
Sep 9, 2011, 9:37:14 PM9/9/11
to scala...@googlegroups.com
Forgive me if there's already a method for doing this--I just looked through the list of Option methods and couldn't find anything, but might have missed it. I'm just wondering if others find the following usage pattern common enough to add a (very simple) method to Option.

Basically:

var o: Option[A]
def f: A => B
var b: B

I frequently do something like:

o match {
    case Some(a) => f(a)
    case _ => b
}

I'd really like to just be able to say "o.applyOrElse(f, b)"

Opinions?

Thanks,
Ken


Alex Cruise

unread,
Sep 9, 2011, 9:40:02 PM9/9/11
to scala...@googlegroups.com
On Fri, Sep 9, 2011 at 6:37 PM, Ken McDonald <ykke...@gmail.com> wrote:
I'd really like to just be able to say "o.applyOrElse(f, b)"

o.map(f).getOrElse(b) innit?

-0xe1a

Kevin Wright

unread,
Sep 9, 2011, 9:40:32 PM9/9/11
to scala...@googlegroups.com
o map f getOrElse b

Tony Morris

unread,
Sep 9, 2011, 9:42:29 PM9/9/11
to scala...@googlegroups.com
class Option[A] {
// All Option methods can be defined in terms of this one
// aka catamorphism
def fold[B](some: A => B, none: => B) =
map(some) getOrElse none
}

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


Tony Morris

unread,
Sep 9, 2011, 9:55:37 PM9/9/11
to scala...@googlegroups.com

Debasish Ghosh

unread,
Sep 10, 2011, 7:50:56 AM9/10/11
to tmo...@tmorris.net, scala...@googlegroups.com
+1 for fold .. just like we have in Either ..

Also if someone can explain why Option extends Product despite itself being a Sum type ..

Thanks.

√iktor Ҡlang

unread,
Sep 10, 2011, 9:43:23 AM9/10/11
to dgh...@acm.org, tmo...@tmorris.net, scala...@googlegroups.com
On Sat, Sep 10, 2011 at 1:50 PM, Debasish Ghosh <ghosh.d...@gmail.com> wrote:
+1 for fold .. just like we have in Either ..

+1!
 



--
Viktor Klang

Akka Tech Lead
Typesafe - Enterprise-Grade Scala from the Experts

Twitter: @viktorklang

Ken McDonald

unread,
Sep 10, 2011, 4:22:58 PM9/10/11
to scala...@googlegroups.com
Boy, talk about being obvious in retrospect. But, that's why I asked--it wasn't obvious in prespect :-) Many thanks.

Ken

Tony Morris

unread,
Sep 10, 2011, 4:23:47 PM9/10/11
to dgh...@acm.org, tmo...@tmorris.net, scala...@googlegroups.com

BTW, we have it on List too, only it is called foldRight.

Reply all
Reply to author
Forward
0 new messages