Jump to content

99 Elm Problems/Problem 7

From Wikibooks, open books for an open world

Flatten a nested list structure.

We have to define a new data type, because lists in Elm are homogeneous.

import Html exposing (text)
import List

type NestedList a
    = Elem a
    | NestedList (List (NestedList a))

flatten : NestedList a -> List a
-- your implementation goes here

main = 
  text <| toString <|
    flatten (NestedList [Elem 1, NestedList [Elem 2, NestedList [Elem 3, Elem 4], Elem 5]])

Result:

[1, 2, 3, 4, 5]

Solutions