Last active
June 29, 2016 20:54
-
-
Save dela3499/c6503e31b2a84cc2374a to your computer and use it in GitHub Desktop.
Implementation of partitionBy function 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, div, span ) | |
import Html.Attributes exposing ( .. ) | |
import Maybe exposing ( withDefault ) | |
import String | |
import Array exposing ( Array ) | |
main = | |
partitionBy String.length ["aa", "a", "b", "b", "cc", "cc", "a", "ab", "bb"] | |
|> toString | |
|> text | |
example = | |
Array.fromList | |
[ Array.fromList ["a1", "b2"] | |
, Array.fromList ["a2", "b2"] | |
, Array.fromList ["a3", "b3"] | |
] | |
nestArray2: a -> Array (Array a) | |
nestArray2 x = | |
Array.fromList | |
[ Array.fromList | |
[x] | |
] | |
partitionBy: (a -> b) -> List a -> List (List a) | |
partitionBy f list = | |
case list of | |
[] -> | |
[] | |
(h::t) -> | |
List.foldl | |
(partitionHelper f) | |
(nestArray2 h, f h) | |
t | |
|> fst | |
|> Array.toList | |
|> List.map Array.toList | |
partitionHelper: (a -> b) -> a -> (Array (Array a), b) -> (Array (Array a), b) | |
partitionHelper f value (arrays, prior) = | |
let fx = f value | |
in | |
if fx == prior | |
then (appendToLastSubarray value arrays, fx) | |
else (Array.push (Array.fromList [ value ]) arrays, fx) | |
appendToLastSubarray: a -> Array (Array a) -> Array (Array a) | |
appendToLastSubarray value arrays = | |
let (firstArrays, lastArray') = splitPop arrays | |
lastArray = lastArray' |> Maybe.withDefault Array.empty | |
in | |
Array.push (Array.push value lastArray) firstArrays | |
splitPop: Array a -> (Array a, Maybe a) | |
splitPop array = | |
let last = Array.length array - 1 | |
in | |
( Array.slice 0 -1 array | |
, Array.get last array | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment