The String module provides functions for working with strings, including concatenation, conversion between strings and character lists, and joining operations.
Description:Concatenates a list of strings, inserting the separator string between each element. This is useful for building comma-separated values, paths, and formatted output.Example:
import Stringlet words = ["Hello", "world", "from", "Elara"]let sentence = join " " words -- "Hello world from Elara"let csv = join "," ["Alice", "Bob", "Charlie"] -- "Alice,Bob,Charlie"let path = join "/" ["home", "user", "documents"] -- "home/user/documents"
Implementation:
let join sep strings = let joinGo acc strings_ = match strings_ with Nil -> acc Cons x Nil -> acc ++ x Cons x xs -> joinGo (acc ++ x ++ sep) xs joinGo "" strings
How join works
The join function uses a tail-recursive helper joinGo with an accumulator. It handles three cases:
Empty list: Returns the accumulator
Single element: Appends it without a separator
Multiple elements: Appends the element and separator, then recurses
import Preludeimport Stringimport Listimport Elara.Prim-- Format a list of key-value pairsdef formatKeyValues : List (String, String) -> Stringlet formatKeyValues pairs = let formatPair pair = match pair with (key, value) -> key ++ ": " ++ value let formatted = List.map formatPair pairs join "\n" formatted-- Count characters in a stringdef countChars : String -> Intlet countChars s = let chars = stringToList s List.length chars -- Assuming length function exists-- Truncate a string to a maximum lengthdef truncate : Int -> String -> Stringlet truncate maxLen s = let chars = stringToList s let truncated = List.take maxLen chars -- Assuming take exists stringFromList truncatedlet main = let info = [ ("Name", "Alice"), ("Age", "25"), ("City", "New York") ] println (formatKeyValues info) *> let longText = "This is a very long string" let short = truncate 10 longText println ("Truncated: " ++ short)
Performance Tip: String concatenation with ++ is O(n) where n is the length of the first string. When building long strings from many pieces, consider using a list accumulator and joining once at the end:
-- Efficient: Build list, join oncelet parts = ["part1", "part2", "part3"]let result = join "" parts-- Less efficient: Multiple concatenationslet result = "part1" ++ "part2" ++ "part3"