stoeffel / list-focus / List.Focus

A list with a focus.

Constructing


type Focus a

A list with a focus.

singleton : a -> Focus a

Create a Focus with a single element.

singleton 1
  |> focused --> 1

append : List a -> Focus a -> Focus a

Append an element to the end of a Focus.

singleton 1
  |> append [2, 3]
  |> toList --> [1, 2, 3]

singleton 1
  |> append [2, 3]
  |> focused --> 1

prepend : List a -> Focus a -> Focus a

Prepend an element to the beginning of a Focus.

singleton 1
  |> prepend [2, 3]
  |> toList --> [2, 3, 1]

singleton 1
  |> prepend [2, 3]
  |> focused --> 1

Deconstructing

focused : Focus a -> a

Get the focused element of a Focus.

singleton 1
  |> focused --> 1

toList : Focus a -> List a

Get the elements of a Focus as a list.

singleton 1
  |> toList --> [1]

Moving

next : Focus a -> Maybe (Focus a)

Move the focus to the next element in a Focus.

singleton 1
  |> append [2, 3]
  |> next
  |> Maybe.map focused --> Just 2

singleton 1
  |> next
  |> Maybe.map focused --> Nothing

singleton 1
  |> append [2, 3]
  |> next
  |> Maybe.map focused --> Just 2

previous : Focus a -> Maybe (Focus a)

Move the focus to the previous element in a Focus.

singleton 1
  |> append [2, 3]
  |> next
  |> Maybe.andThen next
  |> Maybe.andThen previous
  |> Maybe.map focused --> Just 2


singleton 1
  |> previous
  --> Nothing

first : Focus a -> Focus a

Focus first element if list is empty

singleton 1
    |> append [2, 3]
    |> next
    |> Maybe.andThen next
    |> Maybe.map first
    |> Maybe.map focused --> Just 1

singleton 1
    |> append [2, 3, 4]
    |> next
    |> Maybe.andThen next
    |> Maybe.map first
    |> Maybe.map toList --> Just [1, 2, 3, 4]

last : Focus a -> Focus a

Focus last element if list is empty

singleton 1
    |> append [2, 3]
    |> last
    |> focused --> 3

singleton 1
    |> append [2, 3, 4]
    |> last
    |> toList --> [1, 2, 3, 4]

Transforming

map : (a -> b) -> Focus a -> Focus b

Map over a Focus, with information about the focus.

singleton 1
  |> append [2, 3]
  |> map (\x -> x+1)
  |> toList --> [2, 3, 4]

mapParts : { before : Basics.Int -> a -> b, focus : Basics.Int -> a -> b, after : Basics.Int -> a -> b } -> Focus a -> Focus b

Information about the focus.

singleton 1
  |> append [2, 3, 4, 5]
  |> prepend [0]
  |> next
  |> Maybe.map (mapParts
    { before = \i x -> (i, x, "before")
    , focus = \i x -> (i, x, "focus")
    , after = \i x -> (i, x, "after")
    })
   |> Maybe.map toList
--> Just
-->   [ (0, 0, "before")
-->   , (1, 1, "before")
-->   , (2, 2, "focus")
-->   , (3, 3, "after")
-->   , (4, 4, "after")
-->   , (5, 5, "after")
-->   ]

-- Getting all elements after the focus.
singleton 1
  |> append [2, 3, 4, 5]
  |> prepend [0]
  |> next
  |> Maybe.map (mapParts
    { before = \_ _ -> Nothing
    , focus = \_ _ -> Nothing
    , after = \_ -> Just
    })
   |> Maybe.map toList
   |> Maybe.withDefault []
   |> List.filterMap identity
   --> [3, 4, 5]