Given a List[Option[Int]]
:
scala> list
res8: List[Option[Int]] = List(Some(1), Some(2), None)
I can get List(1,2)
, i.e. extract the list
via flatMap
and flatten
:
scala> list.flatten
res9: List[Int] = List(1, 2)
scala> list.flatMap(x => x)
res10: List[Int] = List(1, 2)
Given the following [Maybe Int]
in Haskell, how can I perform the above operation?
I tried the following unsuccessfully:
import Control.Monad
maybeToList :: Maybe a -> [b]
maybeToList Just x = [x]
maybeToList Nothing = []
flatten' :: [Maybe a] -> [a]
flatten' xs = xs >>= (\y -> y >>= maybeToList)
The flatten function is applicable to both Scala's Mutable and Immutable collection data structures. The flatten method will collapse the elements of a collection to create a single collection with elements of the same type.
This is the first method we use to append Scala List using the operator “:+”. The syntax we use in this method is; first to declare the list name and then use the ':+' method rather than the new element that will be appended in the list. The syntax looks like “List name:+ new elements”.
A Seq is an Iterable that has a defined order of elements. Sequences provide a method apply() for indexing, ranging from 0 up to the length of the sequence. Seq has many subclasses including Queue, Range, List, Stack, and LinkedList. A List is a Seq that is implemented as an immutable linked list.
Syntax for defining a Scala List. val variable_name: List[type] = List(item1, item2, item3) or val variable_name = List(item1, item2, item3) A list in Scala is mostly like a Scala array. However, the Scala List is immutable and represents a linked list data structure. On the other hand, Scala array is flat and mutable.
You can use catMaybes
:
import Data.Maybe
catMaybes xs
if you want to use >>=
you need a function Maybe a -> [a]
. This is maybeToList
:
xs >>= maybeToList
As the comment point out, you can convert any Foldable
to a list so you can make flatten'
more general:
flatten' :: Foldable f => [f a] -> [a]
flatten' xs = xs >>= toList
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With