Created
June 12, 2017 23:50
-
-
Save pzp1997/d724379121eba9ca1e4881a35c549f3e to your computer and use it in GitHub Desktop.
Faster(?) implementation of List.Extra.splitAt
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
| 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