Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 31 additions & 11 deletions src/Fifo.elm
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ module Fifo exposing
( Fifo, empty, fromList
, insert, remove
, toList
, length
)

{-|
Expand All @@ -21,13 +22,18 @@ module Fifo exposing

@docs toList


# Inspecting

@docs length

-}


{-| A FIFO containing items of type `a`.
-}
type Fifo a
= Fifo (List a) (List a)
= Fifo (List a) (List a) Int


{-| Creates an empty Fifo.
Expand All @@ -38,7 +44,7 @@ type Fifo a
-}
empty : Fifo a
empty =
Fifo [] []
Fifo [] [] 0


{-| Inserts an item into a Fifo
Expand All @@ -50,8 +56,8 @@ empty =

-}
insert : a -> Fifo a -> Fifo a
insert a (Fifo front back) =
Fifo front (a :: back)
insert a (Fifo front back len) =
Fifo front (a :: back) (len + 1)


{-| Removes the next (oldest) item from a Fifo, returning the item (if any), and the updated Fifo.
Expand All @@ -64,14 +70,14 @@ insert a (Fifo front back) =
remove : Fifo a -> ( Maybe a, Fifo a )
remove fifo =
case fifo of
Fifo [] [] ->
Fifo [] [] _ ->
( Nothing, empty )

Fifo [] back ->
remove <| Fifo (List.reverse back) []
Fifo [] back len ->
remove <| Fifo (List.reverse back) [] len

Fifo (next :: rest) back ->
( Just next, Fifo rest back )
Fifo (next :: rest) back len ->
( Just next, Fifo rest back (len - 1) )


{-| Creates a Fifo from a List.
Expand All @@ -84,7 +90,7 @@ remove fifo =
-}
fromList : List a -> Fifo a
fromList list =
Fifo list []
Fifo list [] (List.length list)


{-| Converts a Fifo to a List.
Expand All @@ -97,5 +103,19 @@ fromList list =

-}
toList : Fifo a -> List a
toList (Fifo front back) =
toList (Fifo front back _) =
front ++ List.reverse back


{-| Returns the number of items in the Fifo.

Fifo.fromList [1, 2, 3]
|> Fifo.remove
|> Tuple.second
|> Fifo.length
-- == 2

-}
length : Fifo a -> Int
length (Fifo _ _ len) =
len
24 changes: 24 additions & 0 deletions tests/Tests.elm
Original file line number Diff line number Diff line change
Expand Up @@ -83,4 +83,28 @@ all =
|> Fifo.remove
|> Tuple.first
|> Expect.equal (Just 2)
, test "length" <|
\() ->
Fifo.fromList [ 1, 2, 3 ]
|> Fifo.length
|> Expect.equal 3
, test "length empty" <|
\() ->
Fifo.empty
|> Fifo.length
|> Expect.equal 0
, test "length insert" <|
\() ->
Fifo.empty
|> Fifo.insert 42
|> Fifo.insert 60
|> Fifo.length
|> Expect.equal 2
, test "length remove" <|
\() ->
Fifo.fromList [ 1, 2, 3 ]
|> Fifo.remove
|> Tuple.second
|> Fifo.length
|> Expect.equal 2
]