Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Flattening" a List in Scala & Haskell

Tags:

haskell

scala

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)
like image 824
Kevin Meredith Avatar asked Aug 19 '14 22:08

Kevin Meredith


People also ask

What is flattening in Scala?

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.

How do I append to a list in Scala?

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”.

What is the difference between SEQ and list in Scala?

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.

How do you define a list in Scala?

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.


1 Answers

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
like image 112
Lee Avatar answered Oct 24 '22 04:10

Lee