The List module provides functions for working with immutable linked lists. Lists in Elara are defined as recursive algebraic data types with two constructors: Nil (empty list) and Cons (element followed by rest of list).
let intersperse sep l = let intersperseGo l_ = match l_ with Nil -> Nil Cons x Nil -> Cons x Nil Cons x xs -> Cons x (Cons sep (intersperseGo xs)) intersperseGo l
let intercalate sep lists = let intercalateGo acc lists_ = match lists_ with Nil -> reverse acc Cons x Nil -> reverse (append x acc) Cons x xs -> intercalateGo (append sep (append x acc)) xs intercalateGo Nil lists
intersperse
intercalate
Use intersperse to insert a separator between elements of a single list.
intersperse 0 [1, 2, 3] -- [1, 0, 2, 0, 3]
Use intercalate to insert a separator list between sublists, then flatten.
let listToString l = let listToStringGo l_ = match l_ with Nil -> "" Cons x Nil -> toString x Cons x xs -> toString x ++ ", " ++ listToStringGo xs match l with Nil -> "[]" Cons x xs -> "[" ++ listToStringGo (Cons x xs) ++ "]"
While not in the List module itself, you can define common higher-order functions:
import Listimport Elara.Primdef map : (a -> b) -> List a -> List blet map f list = match list with Nil -> Nil Cons x xs -> Cons (f x) (map f xs)def filter : (a -> Bool) -> List a -> List alet filter p list = match list with Nil -> Nil Cons x xs -> if p x then Cons x (filter p xs) else filter p xs
append: O(n) where n is the length of the first list
reverse: O(n)
zip: O(min(n, m)) where n and m are the list lengths
flatten: O(n) where n is the total number of elements
intersperse: O(n)
intercalate: O(n * m) where n is the number of lists and m is the average list length
Lists in Elara are singly-linked lists. Appending to the end of a list requires traversing the entire list. For efficient append operations, consider building lists in reverse and calling reverse once at the end.