Created
February 11, 2025 23:10
-
-
Save Janiczek/4086333cd37d01ee2da0bc2854dc4ff4 to your computer and use it in GitHub Desktop.
For some reason ltail is O(n) while rtail is O(1)
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
module SList exposing | |
( SList, empty, fromList, toList | |
, lcons, rcons | |
, lhead, rhead | |
, ltail, rtail | |
, reverse | |
) | |
type SList a | |
= SList ( List a, List a ) | |
empty : SList a | |
empty = | |
SList ( [], [] ) | |
toList : SList a -> List a | |
toList (SList ( x, y )) = | |
x ++ List.reverse y | |
lcons : a -> SList a -> SList a | |
lcons a (SList ( x, y )) = | |
if List.isEmpty y then | |
SList ( [ a ], x ) | |
else | |
SList ( a :: x, y ) | |
rcons : a -> SList a -> SList a | |
rcons a (SList ( y, x )) = | |
if List.isEmpty y then | |
SList ( x, [ a ] ) | |
else | |
SList ( y, a :: x ) | |
lhead : SList a -> Maybe a | |
lhead (SList ( x, y )) = | |
if List.isEmpty x then | |
List.head y | |
else | |
List.head x | |
rhead : SList a -> Maybe a | |
rhead (SList ( y, x )) = | |
if List.isEmpty x then | |
List.head y | |
else | |
List.head x | |
splitInHalf : List a -> ( List a, List a ) | |
splitInHalf xs = | |
splitInHalfHelp xs xs [] | |
splitInHalfHelp : List a -> List a -> List a -> ( List a, List a ) | |
splitInHalfHelp xs ys acc = | |
case ( xs, ys ) of | |
( x :: _ :: xs_, y :: ys_ ) -> | |
splitInHalfHelp xs_ ys_ (y :: acc) | |
_ -> | |
( List.reverse acc, ys ) | |
ltail : SList a -> SList a | |
ltail (SList ( x, y )) = | |
case x of | |
[] -> | |
empty | |
[ _ ] -> | |
let | |
( take, drop ) = | |
splitInHalf y | |
in | |
SList | |
( List.reverse drop | |
, take | |
) | |
_ :: _ -> | |
SList ( List.tail x |> Maybe.withDefault [], y ) | |
rtail : SList a -> SList a | |
rtail (SList ( y, x )) = | |
case x of | |
[] -> | |
empty | |
[ _ ] -> | |
let | |
( take, drop ) = | |
splitInHalf y | |
in | |
SList | |
( take | |
, List.reverse drop | |
) | |
_ :: _ -> | |
SList ( y, List.tail x |> Maybe.withDefault [] ) | |
reverse : SList a -> SList a | |
reverse (SList ( x, y )) = | |
SList ( y, x ) | |
fromList : List a -> SList a | |
fromList l = | |
List.foldl rcons empty l |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment