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

What's the easiest way to flatten nested Options

1 reply
John Ky
Joined: 2009-10-06,
User offline. Last seen 42 years 45 weeks ago.
Hi,

If I have a value that looks something like this:  (0, Some((1, Some(2))))

And I want to flatten it into this: (Some(0), Some(1), Some(2))

What is the easiest and most generic way of doing this?

Cheers,

-John

Tony Morris 2
Joined: 2009-03-20,
User offline. Last seen 42 years 45 weeks ago.
Re: What's the easiest way to flatten nested Options

The easiest and most generic way requires third-party library support
(see Scalaz). What you are describing is called a "Traversable" (see
scalaz.Traverse, specifically the Tuple2[T, _] instance).
This paper describes it best
http://www.comlab.ox.ac.uk/jeremy.gibbons/publications/iterator.pdf

It's a good exercise to play with these abstractions, so I'll leave it here.

John Ky wrote:
> Hi,
>
> If I have a value that looks something like this: (0, Some((1, Some(2))))
>
> And I want to flatten it into this: (Some(0), Some(1), Some(2))
>
> What is the easiest and most generic way of doing this?
>
> Cheers,
>
> -John
>

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