Skip to content

Instantly share code, notes, and snippets.

@pzp1997
Created June 12, 2017 23:50
Show Gist options
  • Select an option

  • Save pzp1997/d724379121eba9ca1e4881a35c549f3e to your computer and use it in GitHub Desktop.

Select an option

Save pzp1997/d724379121eba9ca1e4881a35c549f3e to your computer and use it in GitHub Desktop.
Faster(?) implementation of List.Extra.splitAt
splitAtHybrid : Int -> List a -> ( List a, List a )
splitAtHybrid index list =
if index < 0 then
( [], list )
else
splitAtFast 1 index list
|> Maybe.withDefault ( list, [] )
splitAtFast : Int -> Int -> List a -> Maybe ( List a, List a )
splitAtFast callCnt index list =
case ( index, list ) of
( 0, _ ) ->
Just ( [], list )
( _, [] ) ->
Nothing
( _, x :: xs ) ->
let
splitAtFn =
if callCnt > 1000 then
splitAtSafe []
else
splitAtFast (callCnt + 1)
in
splitAtFn (index - 1) xs
|> Maybe.map (Tuple.mapFirst <| (::) x)
splitAtSafe : List a -> Int -> List a -> Maybe ( List a, List a )
splitAtSafe reversedInit index list =
case list of
[] ->
Nothing
x :: xs ->
if index > 0 then
splitAtSafe (x :: reversedInit) (index - 1) xs
else
Just ( List.reverse reversedInit, list )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment