Created
November 23, 2016 09:04
-
-
Save ccapndave/b83ef93827f745c842d9b9e3eed86de3 to your computer and use it in GitHub Desktop.
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 (Html, div, hr, text) | |
import Array exposing (..) | |
-- Some function taken directly from Array.Extra | |
splitAt : Int -> Array a -> ( Array a, Array a ) | |
splitAt index xs = | |
-- TODO: refactor (written this way to help avoid Array bugs) | |
let | |
len = | |
length xs | |
in | |
case ( index > 0, index < len ) of | |
( True, True ) -> | |
( slice 0 index xs, slice index len xs ) | |
( True, False ) -> | |
( xs, empty ) | |
( False, True ) -> | |
( empty, xs ) | |
( False, False ) -> | |
( empty, empty ) | |
removeAt : Int -> Array a -> Array a | |
removeAt index xs = | |
-- TODO: refactor (written this way to help avoid Array bugs) | |
let | |
( xs0, xs1 ) = | |
splitAt index xs | |
len1 = | |
length xs1 | |
in | |
if len1 == 0 then | |
xs0 | |
else | |
append xs0 (slice 1 len1 xs1) | |
-- A bit of a test harness | |
main = | |
let | |
init : Array String | |
init = Array.fromList ["a", "b", "c", "d", "e"] | |
assert : a -> a -> Html b | |
assert actual expected = | |
if actual /= expected then | |
text <| " × " ++ (toString actual) ++ " /= " ++ (toString expected) | |
else | |
text " ✓" | |
in | |
div [] | |
[ assert init init | |
, hr [] [] | |
, assert (move 0 3 init) (Array.fromList ["b", "c", "d", "a", "e"]) | |
, hr [] [] | |
, assert (move 4 0 init) (Array.fromList ["e", "a", "b", "c", "d"]) | |
, hr [] [] | |
, assert (move 2 3 init) (Array.fromList ["a", "b", "d", "c", "e"]) | |
, hr [] [] | |
, assert (move 3 2 init) (Array.fromList ["a", "b", "d", "c", "e"]) | |
] | |
{-| The function! | |
-} | |
move : Int -> Int -> Array a -> Array a | |
move fromIdx toIdx array = | |
let | |
itemToMove : Maybe a | |
itemToMove = | |
get fromIdx array | |
in | |
case itemToMove of | |
Nothing -> | |
array | |
Just item -> | |
array | |
|> removeAt fromIdx | |
|> splitAt toIdx | |
|> \(l, r) -> append (push item l) r |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment