Created
March 21, 2017 03:38
-
-
Save jschomay/841ab00a6ce38daf3e9b0655dc7dd6bd to your computer and use it in GitHub Desktop.
Nested List example in Elm
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Html exposing (text) | |
import List | |
{- Challenge: flatten an array of arbitrarily nested arrays of integers into a flat array of integers. e.g. [[1,2,[3]],4] -> [1,2,3,4]. | |
(This is a little tricky in Elm because the type system does not allow for lists with different element types. So we have to make a whole new data structure...) | |
-} | |
type NestedList a | |
= Element a | |
| Nested (List (NestedList a)) | |
{-| Turn a NestedList into a normal List. This will "flatten" any nested levels. | |
-} | |
toList : NestedList a -> List a | |
toList nested = | |
let | |
recur node acc = | |
case node of | |
Element a -> | |
a :: acc | |
Nested list -> | |
List.foldr recur acc list | |
in | |
recur nested [] | |
-- equivelent to [[1,2,[3]],4] | |
myNested : NestedList Int | |
myNested = | |
Nested | |
[ Nested | |
[ Element 1 | |
, Element 2 | |
, Nested | |
[ Element 3 ] | |
] | |
, Element 4 | |
] | |
-- equivelent to [1,2,3,4] | |
oneLevel : NestedList Int | |
oneLevel = | |
Nested | |
[ Element 1 | |
, Element 2 | |
, Element 3 | |
, Element 4 | |
] | |
-- equivelent to [1] | |
oneElement : NestedList Int | |
oneElement = | |
Element 1 | |
-- equivelent to [] | |
empty : NestedList Int | |
empty = | |
Nested [ ] | |
-- "poor man's test" (since this is a gist and can be run in http://elm-lang.org/try) | |
-- evaluates to [[1,2,3,4],[1,2,3,4],[1],[]] | |
main = | |
let | |
flattened = | |
[ toList myNested | |
, toList oneLevel | |
, toList oneElement | |
, toList empty | |
] | |
in | |
text <| toString <| flattened |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment