### Example: Multiple Subscriptions Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/Platform_Sub.md An example demonstrating how to combine multiple subscriptions using 'Sub.batch' for keyboard, timer, and window resize events. ```elm -- Multiple subscriptions subscriptions model = Sub.batch [ Browser.Events.onKeyDown keyDecoder , Time.every 1000 Tick , Browser.Events.onResize WindowResized ] ``` -------------------------------- ### Common Task Examples Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/Task.md Illustrates common tasks provided by other libraries, such as getting time, focusing DOM elements, sleeping, and making HTTP requests. ```elm Time.now : Task x Posix -- Get current time Browser.Dom.focus "id" : Task Error () Process.sleep 1000 : Task x () Http.get ... : Task Error String ``` -------------------------------- ### Elm Function Composition Examples Source: https://github.com/elm/core/blob/master/_autodocs/README.md Shows examples of function composition using backward composition and forward piping. ```elm -- Backward composition process = trim << toLower << trim -- Forward pipe result = input |> String.trim |> String.toLower |> parseInteger ``` -------------------------------- ### Example: No Subscriptions Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/Platform_Sub.md An example of a subscriptions function that returns 'Sub.none', indicating no active subscriptions. ```elm -- No subscriptions subscriptions model = Sub.none ``` -------------------------------- ### Example: Combining Multiple Async Operations Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/Task.md Demonstrates combining three asynchronous operations (getting user data, post data, and comments data) into a single task using `Task.map3`. ```elm -- Combining multiple async operations loadPageData : Task Error PageData loadPageData = Task.map3 PageData (getUserData userId) (getPostData postId) (getCommentsData postId) ``` -------------------------------- ### Example: Single Subscription Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/Platform_Sub.md An example of a subscriptions function with a single subscription to a timer event. ```elm -- Single subscription subscriptions model = Time.every 1000 Tick ``` -------------------------------- ### Example: Conditional Subscriptions Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/Platform_Sub.md Shows how to conditionally enable or disable subscriptions based on the application's model state. This example enables a high-frequency timer only when 'isPlaying' is true. ```elm -- Conditional subscriptions subscriptions model = if model.isPlaying then Time.every (1000 / 60) Tick -- 60 FPS else Sub.none ``` -------------------------------- ### Example Usage Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/Array.md Demonstrates practical usage of the Array module functions for creating, querying, manipulating, and transforming arrays. ```APIDOC ## Example Usage ```elm -- Create and manipulate arrays numbers : Array Int numbers = initialize 5 identity -- [0, 1, 2, 3, 4] -- Get elements first : Maybe Int first = get 0 numbers -- Just 0 -- Update elements updated : Array Int updated = set 2 99 numbers -- [0, 1, 99, 3, 4] -- Add elements extended : Array Int extended = push 5 updated -- [0, 1, 99, 3, 4, 5] -- Filter and transform evens : Array Int evens = filter (\x -> modBy 2 x == 0) extended -- Convert to list for list operations listOfNumbers : List Int listOfNumbers = toList extended -- Create from indexed mapping squared : Array Int squared = indexedMap (\i _ -> i * i) (repeat 5 0) ``` ``` -------------------------------- ### Simple Worker Program Example Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/Platform.md This example demonstrates a complete, simple worker program in Elm. It includes initialization, update logic for increment, decrement, and reset messages, and defines the model and message types. ```elm module Counter exposing (main) import Platform import Platform.Cmd as Cmd import Platform.Sub as Sub import Process import Task main : Program () Model Msg main = Platform.worker { init = init, update = update, subscriptions = subscriptions } type alias Model = { count : Int } type Msg = Increment | Decrement | Reset init : () -> (Model, Cmd Msg) init () = ( { count = 0 } , Cmd.none ) update : Msg -> Model -> (Model, Cmd Msg) update msg model = case msg of Increment -> ( { model | count = model.count + 1 } , Cmd.none ) Decrement -> ( { model | count = model.count - 1 } , Cmd.none ) Reset -> ( { model | count = 0 } , Cmd.none ) subscriptions : Model -> Sub Msg subscriptions _ = Sub.none ``` -------------------------------- ### Bitwise AND Operation Examples Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/Bitwise.md Demonstrates the bitwise AND operation. Use this to check if specific bits are set in a number. ```elm and 15 7 == 7 -- 1111 & 0111 = 0111 and 12 10 == 8 -- 1100 & 1010 = 1000 ``` -------------------------------- ### Bitwise OR Operation Examples Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/Bitwise.md Demonstrates the bitwise OR operation. Use this to set specific bits in a number. ```elm or 8 4 == 12 -- 1000 | 0100 = 1100 or 12 10 == 14 -- 1100 | 1010 = 1110 ``` -------------------------------- ### Example Usage: Convert Character to Uppercase Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/Char.md A simple example showing the direct application of `Char.toUpper` to a character. ```elm -- Convert a character uppered : Char -> Char uppered = Char.toUpper ``` -------------------------------- ### Example Usage: Simple Command Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/Platform_Cmd.md Demonstrates the use of `Cmd.none` within an Elm `update` function when no action is required. ```elm -- Simple command that does nothing update : Msg -> Model -> (Model, Cmd Msg) update msg model = case msg of NoOp -> (model, Cmd.none) ``` -------------------------------- ### Example Usage: Working with Coordinates Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/Tuple.md Demonstrates defining a point as a tuple and calculating its distance from the origin using tuple access. ```elm -- Working with coordinates point : (Float, Float) point = (3, 4) distance : (Float, Float) -> Float distance (x, y) = sqrt (x ^ 2 + y ^ 2) distance point == 5 ``` -------------------------------- ### Create Empty Set Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/Set.md Initializes an empty set. Use this as a starting point for building sets. ```elm empty : Set Int ``` -------------------------------- ### Example: Sequential Task Execution Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/Task.md Demonstrates how to chain multiple tasks sequentially using `andThen` and `map` to process results from multiple file reads. ```elm -- Sequential task execution readFiles : Task Error (String, String) readFiles = readFile "config.json" |> andThen (\config -> readFile "data.json" |> map (\data -> (config, data))) ``` -------------------------------- ### Spawn Concurrent Tasks Example Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/Process.md Shows how to spawn multiple tasks concurrently using Http.get and Task.attempt to fetch users and posts simultaneously. ```elm -- Spawn concurrent tasks type Msg = FetchUsers | GotUsers (Result Error (List User)) | GotPosts (Result Error (List Post)) update msg model = case msg of FetchUsers -> let usersTask = Http.get "/users" usersDecoder postsTask = Http.get "/posts" postsDecoder in ( { model | loading = True } , Cmd.batch [ Task.attempt GotUsers usersTask , Task.attempt GotPosts postsTask ] ) ``` -------------------------------- ### Example Usage: Format Price Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/String.md Shows how to format a floating-point number into a currency string by prepending a dollar sign. Assumes `fromFloat` is available for conversion. ```elm -- Format numbers formatPrice : Float -> String formatPrice price = "$" ++ fromFloat price ``` -------------------------------- ### Example Usage: Word Count Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/String.md Calculates the number of words in a string by splitting the string into words using `words` and then getting the length of the resulting list. ```elm -- Word count wordCount : String -> Int wordCount text = text |> words |> List.length ``` -------------------------------- ### empty Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/Set.md Creates an empty set, serving as the starting point for set operations. ```APIDOC ## `empty : Set a` Create an empty set. ``` -------------------------------- ### empty Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/Dict.md Creates an empty dictionary. This is the starting point for building new dictionaries. ```APIDOC ## empty ### Description Create an empty dictionary. ### Type Signature ```elm empty : Dict k v ``` ### Example ```elm empty : Dict String Int ``` ``` -------------------------------- ### Example Usage: Batching Commands Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/Platform_Cmd.md Shows how to use `Cmd.batch` to execute multiple HTTP requests concurrently within an Elm `update` function. ```elm -- Batch multiple commands update msg model = case msg of LoadData -> let fetchUsers = Http.get { url = "/users", expect = ... } fetchPosts = Http.get { url = "/posts", expect = ... } in (model, Cmd.batch [ fetchUsers, fetchPosts ]) ``` -------------------------------- ### Example: Parsing Configuration with Detailed Errors Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/Result.md Demonstrates parsing a configuration string, handling potential errors like invalid host or port formats, and returning a structured Result. ```elm -- Parse configuration with detailed errors type ConfigError = InvalidPort String | InvalidHost String parseConfig : String -> Result ConfigError { host : String, port : Int } parseConfig input = case String.split ":" input of [host, portStr] -> case String.toInt portStr of Just port -> if port >= 0 && port <= 65535 then Ok { host = host, port = port } else Err (InvalidPort portStr) Nothing -> Err (InvalidPort portStr) _ -> Err (InvalidHost input) ``` -------------------------------- ### Bitwise XOR Operation Examples Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/Bitwise.md Demonstrates the bitwise XOR operation. Use this to toggle specific bits in a number. ```elm xor 12 10 == 6 -- 1100 ^ 1010 = 0110 xor 7 3 == 4 -- 0111 ^ 0011 = 0100 ``` -------------------------------- ### Bitwise Complement Operation Examples Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/Bitwise.md Demonstrates the bitwise complement (NOT) operation. This flips each bit individually. ```elm complement 0 == -1 complement -1 == 0 ``` -------------------------------- ### Example: Track Unique User IDs Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/Set.md Demonstrates using a set to efficiently track unique integer IDs. Includes checking for membership and adding new IDs. ```elm -- Track unique user IDs seenIds : Set Int seenIds = fromList [1, 2, 3, 4, 5] -- Check if we've seen this ID before hasSeenId : Int -> Bool hasSeenId id = member id seenIds -- Add new IDs newSeenIds : Set Int newSeenIds = insert 6 seenIds ``` -------------------------------- ### Delayed Notification Example Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/Process.md Creates a command to display a notification after a 3-second delay using Process.sleep and Task.perform. ```elm -- Delayed notification showDelayedNotification : String -> Cmd Msg showDelayedNotification msg = Process.sleep 3000 |> Task.andThen (\() -> Task.succeed (DisplayNotification msg)) |> Task.perform identity ``` -------------------------------- ### singleton Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/Dict.md Creates a dictionary containing a single key-value pair. Useful for initializing dictionaries with a starting element. ```APIDOC ## singleton ### Description Create a dictionary with one key-value pair. ### Type Signature ```elm singleton : comparable -> v -> Dict comparable v ``` ### Example ```elm singleton "Tom" 1 singleton "Alice" { age = 28, height = 1.65 } ``` ``` -------------------------------- ### Example Usage of Array Module Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/Array.md Demonstrates common operations like creating, accessing, updating, adding, filtering, and transforming arrays, along with list conversions. ```elm -- Create and manipulate arrays numbers : Array Int numbers = initialize 5 identity -- [0, 1, 2, 3, 4] -- Get elements first : Maybe Int first = get 0 numbers -- Just 0 -- Update elements updated : Array Int updated = set 2 99 numbers -- [0, 1, 99, 3, 4] -- Add elements extended : Array Int extended = push 5 updated -- [0, 1, 99, 3, 4, 5] -- Filter and transform evens : Array Int evens = filter (\x -> modBy 2 x == 0) extended -- Convert to list for list operations listOfNumbers : List Int listOfNumbers = toList extended -- Create from indexed mapping squared : Array Int squared = indexedMap (\i _ -> i * i) (repeat 5 0) ``` -------------------------------- ### Example Usage: Transforming Tuples Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/Tuple.md Shows how to use `mapBoth` to transform both elements of a coordinate tuple, effectively doubling the coordinates. ```elm -- Transforming tuples doubleCoordinates : (Float, Float) -> (Float, Float) doubleCoordinates = mapBoth (\x -> x * 2) (\y -> y * 2) doubleCoordinates (3, 4) == (6, 8) ``` -------------------------------- ### Left Bit Shift Operation Examples Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/Bitwise.md Demonstrates shifting bits to the left. This is equivalent to multiplying by powers of two. ```elm shiftLeftBy 1 5 == 10 -- 101 << 1 = 1010 (5 * 2) shiftLeftBy 5 1 == 32 -- 1 << 5 = 100000 (1 * 32) shiftLeftBy 1 -1 == -2 ``` -------------------------------- ### Elm Dict - Count Users Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/Dict.md Demonstrates how to get the total number of users in the dictionary using `Dict.size`. ```elm -- Count users userCount : Int userCount = Dict.size users ``` -------------------------------- ### map Helper Function Examples Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/Maybe.md Shows how `map` applies a function to the value inside a `Just`. If the `Maybe` is `Nothing`, the result remains `Nothing`. ```elm map sqrt (Just 9) == Just 3 map sqrt Nothing == Nothing map sqrt (String.toFloat "9") == Just 3 map sqrt (String.toFloat "x") == Nothing ``` -------------------------------- ### map3 Helper Function Examples Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/Maybe.md Demonstrates `map3`, which applies a function to three `Maybe` values only if all are `Just`. If any is `Nothing`, the result is `Nothing`. ```elm map3 (\x y z -> x + y + z) (Just 1) (Just 2) (Just 3) == Just 6 map3 (\x y z -> x + y + z) (Just 1) Nothing (Just 3) == Nothing ``` -------------------------------- ### Example Usage: Work with Unicode Characters Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/Char.md Shows how to create characters from Unicode code points using `Char.fromCode` and retrieve code points using `Char.toCode`, including emojis. ```elm -- Work with Unicode emoji : Char emoji = Char.fromCode 0x1F600 -- 😀 emojiCode : Int emojiCode = Char.toCode '😃' -- 0x1F603 ``` -------------------------------- ### Create an Empty Dictionary in Elm Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/Dict.md Initializes an empty dictionary. This is the starting point for building a new dictionary. ```elm empty : Dict String Int ``` -------------------------------- ### Example: Find Unique Tags Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/Set.md Illustrates converting a list of strings, potentially with duplicates, into a set to obtain a collection of unique tags. ```elm -- Find unique tags tags : List String tags = ["elm", "functional", "elm", "language", "functional"] uniqueTags : Set String uniqueTags = fromList tags ``` -------------------------------- ### Elm Dict - Get a User Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/Dict.md Shows how to retrieve a user from the dictionary by their ID using `Dict.get`. ```elm -- Get a user getUser : String -> Maybe User getUser id = Dict.get id users ``` -------------------------------- ### Example: Delayed Task with Sleep and Notification Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/Task.md Illustrates a simple asynchronous operation involving a delay using `Process.sleep` followed by a notification task. ```elm -- With Time delayedTask : Task Never () delayedTask = Process.sleep 1000 |> andThen (\() -> sendNotification "Done!") ``` -------------------------------- ### Example: Set Operations for Teams Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/Set.md Shows practical application of set operations like union, intersection, and difference using string sets to represent team members. ```elm -- Set operations team1 = fromList ["alice", "bob", "charlie"] team2 = fromList ["bob", "charlie", "diana"] bothTeams = union team1 team2 -- ["alice", "bob", "charlie", "diana"] overlap = intersect team1 team2 -- ["bob", "charlie"] onlyTeam1 = diff team1 team2 -- ["alice"] ``` -------------------------------- ### withDefault Helper Function Examples Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/Maybe.md Demonstrates how `withDefault` provides a fallback value when the `Maybe` is `Nothing`. It's useful for converting an optional value into a required one. ```elm withDefault 100 (Just 42) == 42 withDefault 100 Nothing == 100 withDefault "unknown" (Dict.get "Tom" Dict.empty) == "unknown" ``` -------------------------------- ### Example Usage: Zipping Lists with `pair` and `map2` Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/Tuple.md Demonstrates a `zip` function that combines two lists into a list of pairs using `List.map2` and the `pair` function. ```elm -- Using with List.map2 zip : List a -> List b -> List (a, b) zip xs ys = List.map2 pair xs ys zip [1, 2, 3] ["a", "b", "c"] == [(1, "a"), (2, "b"), (3, "c")] ``` -------------------------------- ### Example: Error Handling with Attempt Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/Task.md Shows how to safely fetch user data using `Http.get` and handle potential errors by wrapping the result in another `Result` type. ```elm -- Error handling fetchUserSafely : Int -> Task Never (Result Error User) fetchUserSafely id = Http.get "/users/" id |> attempt Ok |> map (mapError Error) |> perform identity ``` -------------------------------- ### get Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/Dict.md Retrieves the value associated with a specific key. Returns `Just value` if the key is found, and `Nothing` otherwise. ```APIDOC ## get ### Description Get the value associated with a key. ### Type Signature ```elm get : comparable -> Dict comparable v -> Maybe v ``` ### Example ```elm animals = fromList [ ("Tom", Cat), ("Jerry", Mouse) ] get "Tom" animals == Just Cat get "Jerry" animals == Just Mouse get "Spike" animals == Nothing ``` ``` -------------------------------- ### Sleep Function Examples Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/Process.md Demonstrates the usage of the Process.sleep function to block progress on the current process for a specified number of milliseconds. ```elm sleep 1000 -- Sleep for 1 second sleep 100 -- Sleep for 0.1 seconds -- Example: Delayed action delayedGreeting : Task Never () delayedGreeting = Task.sequence [ Task.succeed (Debug.log "Starting..." ()) , Process.sleep 2000 , Task.succeed (Debug.log "Done!" ()) ] ``` -------------------------------- ### Check if String Starts With Substring in Elm Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/String.md Illustrates the `startsWith` function for verifying if a string begins with a given prefix. The comparison is case-sensitive. ```elm startsWith "the" "theory" == True startsWith "ory" "theory" == False ``` -------------------------------- ### Example: Mapping Component Subscriptions Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/Platform_Sub.md Illustrates how to map subscriptions from child components (User and Page) to the main application's message type using 'Sub.map'. ```elm -- Map subscriptions from a component type Msg = UserMsg UserMsg | PageMsg PageMsg subscriptions model = Sub.batch [ Sub.map UserMsg (User.subscriptions model.user) , Sub.map PageMsg (Page.subscriptions model.page) ] ``` -------------------------------- ### Example Usage: Working with Pairs in a List Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/Tuple.md Illustrates extracting the first names from a list of (String, String) tuples using `List.map` and the `first` function. ```elm -- Working with pairs names : List (String, String) names = [ ("Alice", "Smith") , ("Bob", "Jones") , ("Charlie", "Brown") ] firstNames : List String firstNames = List.map first names -- ["Alice", "Bob", "Charlie"] ``` -------------------------------- ### Kill Process Example Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/Process.md Illustrates how to kill a spawned process using its Id. This stops the task the process was running, even if it involves an ongoing HTTP request. ```elm type Msg = Spawned Id | Stop update msg model = case msg of Spawned processId -> ({ model | process = Just processId }, Cmd.none) Stop -> case model.process of Just processId -> (model, Task.attempt (\_ -> ProcessKilled) (Process.kill processId)) Nothing -> (model, Cmd.none) ``` -------------------------------- ### Example Usage: Handling Optional Record Fields Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/Maybe.md Illustrates using `Maybe` for optional fields in a record and accessing them with a default value using `withDefault`. ```elm -- Handling optional record fields type alias Person = { name : String, age : Maybe Int } tom = { name = "Tom", age = Just 42 } sue = { name = "Sue", age = Nothing } -- Getting person's age with default getAge person = withDefault 0 person.age ``` -------------------------------- ### Example Usage: Case-Insensitive Comparison Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/String.md Compares two strings for equality, ignoring case. It converts both strings to lowercase before comparison. ```elm -- Case-insensitive comparison isSame : String -> String -> Bool isSame a b = toLower a == toLower b ``` -------------------------------- ### Elm Dict - Get All User Names Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/Dict.md Shows how to extract all user names from the dictionary using `Dict.values` and `List.map`. ```elm -- Get all names names : List String names = Dict.values users |> List.map .name ``` -------------------------------- ### Example Usage: Chaining Optional Operations Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/Maybe.md Demonstrates chaining multiple `Maybe`-returning operations using `andThen` to process input sequentially, with failure at any step halting the chain. ```elm -- Chaining optional operations parseBirthday : String -> Maybe Date parseBirthday input = String.toInt input |> andThen validateYear |> andThen lookupBirthday ``` -------------------------------- ### andThen Helper Function Example Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/Maybe.md Shows how `andThen` chains computations that return `Maybe`. The next computation only runs if the previous one resulted in `Just`. ```elm parseMonth : String -> Maybe Int parseMonth userInput = String.toInt userInput |> andThen toValidMonth toValidMonth : Int -> Maybe Int toValidMonth month = if 1 <= month && month <= 12 then Just month else Nothing parseMonth "4" == Just 4 parseMonth "9" == Just 9 parseMonth "a" == Nothing parseMonth "0" == Nothing ``` -------------------------------- ### Example Usage: Transforming Optionals with map Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/Maybe.md Shows how `map` can be used to transform the value within a `Maybe` context, such as doubling an age if it exists. ```elm -- Using map to transform optionals doubleAge : Maybe Int -> Maybe Int doubleAge maybeAge = map (\age -> age * 2) maybeAge ``` -------------------------------- ### map2 Helper Function Examples Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/Maybe.md Illustrates `map2`, which applies a function to two `Maybe` values only if both are `Just`. If either is `Nothing`, the result is `Nothing`. ```elm map2 (+) (Just 3) (Just 4) == Just 7 map2 (+) (Just 3) Nothing == Nothing map2 (+) Nothing (Just 4) == Nothing map2 (+) (String.toInt "1") (String.toInt "123") == Just 124 ``` -------------------------------- ### Elm Immutability Example Source: https://github.com/elm/core/blob/master/_autodocs/README.md Illustrates Elm's immutability principle where operations return new values instead of modifying existing ones. ```elm list = [1, 2, 3] newList = List.map ( x -> x * 2) list -- list is unchanged, newList is [2, 4, 6] ``` -------------------------------- ### Elm Type Safety Example Source: https://github.com/elm/core/blob/master/_autodocs/README.md Demonstrates how the Elm type system prevents errors at compile time, showing both an incorrect usage and its proper correction. ```elm -- Type mismatch at compile time List.map String.toInt ["1", "2", "3"] -- Error: map expects List String -- Proper usage List.filterMap String.toInt ["1", "two", "3"] -- [1, 3] ``` -------------------------------- ### Logical Right Bit Shift (Zero-Fill) Operation Examples Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/Bitwise.md Demonstrates shifting bits to the right and filling new bits with zeros. Useful for unsigned integer interpretations. ```elm shiftRightZfBy 1 32 == 16 -- 100000 >>> 1 = 10000 shiftRightZfBy 2 32 == 8 -- 100000 >>> 2 = 1000 shiftRightZfBy 1 -32 == 2147483632 -- Zeros fill from left ``` -------------------------------- ### Polling with Delays Example Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/Process.md Implements a polling mechanism that repeatedly checks for updates with a 5-second delay between checks using recursive Task execution. ```elm -- Polling with delays pollForUpdates : Task Never () pollForUpdates = checkForUpdates |> Task.andThen (\_ -> Process.sleep 5000) |> Task.andThen (\() -> pollForUpdates) ``` -------------------------------- ### Get Substrings Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/String.md Functions for extracting substrings from a string using start and end indices, or by taking/dropping characters from the left or right side. ```APIDOC ## Get Substrings ### `slice : Int -> Int -> String -> String` Take a substring given start and end indices. Negative indices count from the end. ```elm slice 7 9 "snakes on a plane!" == "on" slice 0 6 "snakes on a plane!" == "snakes" slice 0 -7 "snakes on a plane!" == "snakes on a" slice -6 -1 "snakes on a plane!" == "plane" ``` ### `left : Int -> String -> String` Take n characters from the left side. ```elm left 2 "Mulder" == "Mu" ``` ### `right : Int -> String -> String` Take n characters from the right side. ```elm right 2 "Scully" == "ly" ``` ### `dropLeft : Int -> String -> String` Drop n characters from the left side. ```elm dropLeft 2 "The Lone Gunmen" == "e Lone Gunmen" ``` ### `dropRight : Int -> String -> String` Drop n characters from the right side. ```elm dropRight 2 "Cigarette Smoking Man" == "Cigarette Smoking M" ``` ``` -------------------------------- ### Example Usage: Parse and Validate Email Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/String.md Demonstrates parsing and validating an email string by trimming whitespace, converting to lowercase, and checking for the presence of '@' and minimum length. ```elm -- Parse and validate input parseEmail : String -> Maybe String parseEmail input = let trimmed = trim (toLower input) in if contains "@" trimmed && length trimmed > 5 then Just trimmed else Nothing ``` -------------------------------- ### Example Usage: Mapping Commands Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/Platform_Cmd.md Illustrates how `Cmd.map` is used to adapt a command's messages to the main application's message type, typically when dealing with component-specific commands. ```elm -- Map a command type Msg = UserMsg UserMsg | PageMsg PageMsg update msg model = case msg of UserMsg userMsg -> let (userModel, userCmd) = User.update userMsg model.user in ( { model | user = userModel } , Cmd.map UserMsg userCmd ) ``` -------------------------------- ### Comparable Type Constraint Example Source: https://github.com/elm/core/blob/master/_autodocs/types.md Shows the 'comparable' type constraint, used for types that can be compared for ordering. This is required for elements in Sets and keys in Dicts. ```elm (<) : comparable -> comparable -> Bool compare : comparable -> comparable -> Order ``` -------------------------------- ### Add Character to String Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/String.md Prepends a character to the beginning of a string. Use this when you need to construct a new string with an added character at the start. ```elm cons 'T' "he truth is out there" == "The truth is out there" ``` -------------------------------- ### Basic Functions Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/String.md Provides essential string manipulation functions including checking for emptiness, getting the length, reversing, repeating, and replacing substrings. ```APIDOC ## Basic Functions ### `isEmpty : String -> Bool` Determine if a string is empty. ```elm isEmpty "" == True isEmpty "the world" == False ``` ### `length : String -> Int` Get the length of a string. ```elm length "innumerable" == 11 length "" == 0 ``` ### `reverse : String -> String` Reverse a string. ```elm reverse "stressed" == "desserts" ``` ### `repeat : Int -> String -> String` Repeat a string n times. ```elm repeat 3 "ha" == "hahaha" ``` ### `replace : String -> String -> String -> String` Replace all occurrences of one substring with another. ```elm replace "." "-" "Json.Decode.succeed" == "Json-Decode-succeed" replace "," "/" "a,b,c,d,e" == "a/b/c/d/e" ``` ``` -------------------------------- ### Example Usage: Parse CSV Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/String.md Illustrates parsing a CSV string into a list of lists of strings. It uses `lines` to split into rows and `List.map` with `split` to parse each row into fields. ```elm -- Process CSV parseCSV : String -> List (List String) parseCSV csv = csv |> lines |> List.map (split ",") ``` -------------------------------- ### Example Usage: Emphasize Text Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/String.md A simple function to wrap a given string with double asterisks, commonly used for markdown formatting to emphasize text. ```elm -- Transform text emphasize : String -> String emphasize text = "**" ++ text ++ "**" ``` -------------------------------- ### Arithmetic Right Bit Shift Operation Examples Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/Bitwise.md Demonstrates shifting bits to the right while preserving the sign bit. This is equivalent to dividing by powers of two. ```elm shiftRightBy 1 32 == 16 -- 100000 >> 1 = 10000 (32 / 2) shiftRightBy 2 32 == 8 -- 100000 >> 2 = 1000 (32 / 4) shiftRightBy 1 -32 == -16 -- Sign bit preserved ``` -------------------------------- ### Create a Range of Integers Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/List.md Generate a list of integers within a specified inclusive range using `range`. If the start is greater than the end, an empty list is produced. ```elm range 3 6 == [3, 4, 5, 6] range 3 3 == [3] range 6 3 == [] ``` -------------------------------- ### Example: Chaining Multiple Operations Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/Result.md Illustrates chaining multiple validation steps using `andThen` and transforming the final result with `map`. This pattern is common for complex data processing pipelines. ```elm -- Chain multiple operations validateUser : User -> Result String User validateUser user = Ok user |> andThen validateEmail |> andThen validateAge |> map normalizeData ``` -------------------------------- ### Get String Length in Elm Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/String.md Shows how to use the `length` function to get the number of characters in a string. Returns 0 for an empty string. ```elm length "innumerable" == 11 length "" == 0 ``` -------------------------------- ### List Utility Functions Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/List.md Provides essential utility functions for lists, including getting the length, reversing the list, checking for element membership, verifying if all or any elements satisfy a condition, and finding the maximum or minimum element. It also includes functions for calculating the sum and product of list elements. ```APIDOC ## Utilities ### `length : List a -> Int` Determine the length of a list. ```elm length [1, 2, 3] == 3 length [] == 0 ``` ### `reverse : List a -> List a` Reverse a list. ```elm reverse [1, 2, 3, 4] == [4, 3, 2, 1] ``` ### `member : a -> List a -> Bool` Figure out whether a list contains a value. ```elm member 9 [1, 2, 3, 4] == False member 4 [1, 2, 3, 4] == True ``` ### `all : (a -> Bool) -> List a -> Bool` Determine if all elements satisfy a test. ```elm all isEven [2, 4] == True all isEven [2, 3] == False all isEven [] == True ``` ### `any : (a -> Bool) -> List a -> Bool` Determine if any element satisfies a test. ```elm any isEven [2, 3] == True any isEven [1, 3] == False any isEven [] == False ``` ### `maximum : List comparable -> Maybe comparable` Find the maximum element in a list. ```elm maximum [1, 4, 2] == Just 4 maximum [] == Nothing ``` ### `minimum : List comparable -> Maybe comparable` Find the minimum element in a list. ```elm minimum [3, 2, 1] == Just 1 minimum [] == Nothing ``` ### `sum : List number -> number` Get the sum of the list elements. ```elm sum [1, 2, 3] == 6 sum [] == 0 ``` ### `product : List number -> number` Get the product of the list elements. ```elm product [2, 2, 2] == 8 product [] == 1 ``` ``` -------------------------------- ### Unary Operations Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/Basics.md Functions for negating numbers, getting absolute values, and clamping numbers within a range. ```APIDOC ## Unary Operations ### `negate : number -> number` Negate a number. ```elm negate 42 == -42 negate -42 == 42 negate 0 == 0 ``` ### `abs : number -> number` Get the absolute value of a number. ```elm abs 16 == 16 abs -4 == 4 abs -8.5 == 8.5 ``` ### `clamp : number -> number -> number -> number` Clamp a number within a given range. ```elm clamp 100 200 50 == 100 clamp 100 200 150 == 150 clamp 100 200 250 == 200 ``` ``` -------------------------------- ### Get the Size of an Elm Dict Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/Dict.md Returns the total number of key-value pairs currently stored in the dictionary. ```elm size empty == 0 size (fromList [("a", 1), ("b", 2)]) == 2 ``` -------------------------------- ### Number Type Constraint Example Source: https://github.com/elm/core/blob/master/_autodocs/types.md Illustrates the 'number' type constraint, which applies to types that support arithmetic operations like addition and square root. Note that sqrt is restricted to Float. ```elm (+) : number -> number -> number sqrt : Float -> Float -- Note: restricted to Float ``` -------------------------------- ### Get Array Length Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/Array.md Returns the total number of elements in an array. Useful for iteration or size checks. ```elm length (fromList [1, 2, 3]) == 3 ``` -------------------------------- ### take Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/List.md Takes the first `n` elements from a list. If `n` is greater than the list length, the entire list is returned. ```APIDOC ## `take : Int -> List a -> List a` ### Description Take the first n members of a list. ### Method N/A (Function Signature) ### Parameters - **Int**: The number of elements to take from the beginning of the list. - **List a**: The list from which to take elements. ### Response - **List a**: A new list containing the first `n` elements. ### Example ```elm take 2 [1, 2, 3, 4] == [1, 2] take 10 [1, 2] == [1, 2] ``` ``` -------------------------------- ### Get Size of Set Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/Set.md Returns the total number of unique elements in the set. Useful for understanding set cardinality. ```elm size empty == 0 size (fromList [1, 2, 3]) == 3 ``` -------------------------------- ### Elm Dict - Store User Information Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/Dict.md Demonstrates how to define a user type alias and create a dictionary of users using `Dict.fromList`. ```elm -- Store user information type alias User = { name : String , age : Int , email : String } users : Dict String User users = Dict.fromList [ ("alice", User "Alice" 28 "alice@example.com") , ("bob", User "Bob" 35 "bob@example.com") ] ``` -------------------------------- ### Example Usage: Filter Alphanumeric Characters Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/Char.md Illustrates filtering a string to keep only alphanumeric characters using `Char.isAlphaNum` and `String.filter`. ```elm -- Filter alphanumeric characters cleanString : String -> String cleanString = String.filter Char.isAlphaNum cleanString "Hello-World!" == "HelloWorld" ``` -------------------------------- ### Example Usage: Check if String Contains Only Digits Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/Char.md Demonstrates using `Char.isDigit` with `String.all` to check if all characters in a string are digits. ```elm -- Check if a string contains only digits isNumeric : String -> Bool isNumeric str = String.all Char.isDigit str isNumeric "12345" == True isNumeric "123a5" == False ``` -------------------------------- ### Get the Length of a List Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/List.md The `length` function returns the number of elements in a list. It is a common utility for understanding list size. ```elm length [1, 2, 3] == 3 length [] == 0 ``` -------------------------------- ### Get All Keys from Elm Dict Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/Dict.md Extracts all keys from the dictionary and returns them as a sorted list. The keys are ordered from lowest to highest. ```elm keys (fromList [("b", 1), ("a", 2)]) == ["a", "b"] ``` -------------------------------- ### Convert Character to Locale-Aware Lowercase Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/Char.md Use `toLocaleLower` for locale-specific lowercase conversion. This function is available but has no specific examples provided in the documentation. -------------------------------- ### todo Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/Debug.md Acts as a placeholder for code that will be written later. When encountered, it throws an uncatchable runtime exception, signaling incomplete logic. ```APIDOC ## `todo` ### Description A placeholder for code that you will write later. Useful when developing union types incrementally. If encountered, it throws an uncatchable runtime exception. ### Type Signature `String -> a` ### Examples ```elm type Entity = Ship | Fish | Captain | Seagull drawEntity entity = case entity of Ship -> ... Fish -> ... _ -> Debug.todo "handle Captain and Seagull" ``` ### Limitations - Not available with `elm make --optimize`. - Not available in packages. - Causes uncatchable runtime exceptions. - Uncatchable runtime exceptions should not appear in production applications. Use `Maybe` and `Result` types instead. ``` -------------------------------- ### Running Asynchronous Code with Tasks Source: https://github.com/elm/core/blob/master/_autodocs/README.md Demonstrates how to handle asynchronous operations within the Elm update function using Tasks. It shows how to initiate a task and handle its success or failure. ```elm update msg model = case msg of LoadData -> ( model , Task.attempt GotData fetchData ) GotData (Ok data) -> ({ model | data = Just data }, Cmd.none) GotData (Err error) -> ({ model | error = Just error }, Cmd.none) ``` -------------------------------- ### Get All Values from Elm Dict Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/Dict.md Extracts all values from the dictionary and returns them as a list. The order of values corresponds to the sorted order of their keys. ```elm values (fromList [("b", 1), ("a", 2)]) == [2, 1] ``` -------------------------------- ### Create a Singleton List Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/List.md Use `singleton` to create a list containing exactly one element. This is useful for initializing lists or when an operation requires a list but you only have a single value. ```elm singleton 1234 == [1234] singleton "hi" == ["hi"] ``` -------------------------------- ### Array Query Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/Array.md Functions to query the state of an array, such as checking if it's empty, getting its length, or retrieving an element at a specific index. ```APIDOC ## Query ### `isEmpty : Array a -> Bool` Determine if an array is empty. ```elm isEmpty empty == True isEmpty (fromList [1, 2, 3]) == False ``` ### `length : Array a -> Int` Return the length of an array. ```elm length (fromList [1, 2, 3]) == 3 ``` ### `get : Int -> Array a -> Maybe a` Get the element at the given index. Returns `Nothing` if the index is out of bounds. ```elm get 0 (fromList [3, 2, 1]) == Just 3 get 2 (fromList [3, 2, 1]) == Just 1 get 5 (fromList [3, 2, 1]) == Nothing ``` ``` -------------------------------- ### Get Element by Index Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/Array.md Retrieves the element at a specific index in the array. Returns `Just element` if the index is valid, and `Nothing` if the index is out of bounds. ```elm get 0 (fromList [3, 2, 1]) == Just 3 ``` ```elm get 2 (fromList [3, 2, 1]) == Just 1 ``` ```elm get 5 (fromList [3, 2, 1]) == Nothing ``` -------------------------------- ### Slice Array Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/Array.md Extracts a sub-array from a given start index to an end index (exclusive). Supports negative indexes for counting from the end. ```elm slice 1 3 (fromList [0, 1, 2, 3, 4]) == fromList [1, 2] ``` ```elm slice 0 -1 (fromList [0, 1, 2, 3, 4]) == fromList [0, 1, 2, 3] ``` -------------------------------- ### Sort List with Custom Comparison Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/List.md Sorts a list using a custom comparison function to define the order. This example reverses the natural order. ```elm sortWith flippedComparison [1, 2, 3, 4, 5] == [5, 4, 3, 2, 1] flippedComparison a b = case compare a b of LT -> GT EQ -> EQ GT -> LT ``` -------------------------------- ### (|>) Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/Basics.md Forward pipe operator. `x |> f` is equivalent to `f x`. ```APIDOC ## (|>) : a -> (a -> b) -> b ### Description Forward pipe operator. `x |> f` is equivalent to `f x`. ### Signature `(|>) : a -> (a -> b) -> b` ### Examples ```elm 5 |> sqrt == sqrt 5 input |> String.trim |> String.toUpper ``` ``` -------------------------------- ### spawn Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/Process.md Runs a given Task in its own light-weight process, enabling concurrent execution. The spawned process cannot receive messages, and the runtime interleaves progress between tasks. ```APIDOC ## spawn ### Description Run a task in its own light-weight process. This allows multiple tasks to run concurrently, with the runtime interleaving their progress. ### Type Signature `spawn : Task x a -> Task y Id` ### Parameters * **task** (`Task x a`) - The task to run in a new process. ### Returns * `Task y Id` - A task that, when run, spawns the process and returns its `Id`. ### Example ```elm spawn task1 |> andThen (\_ -> spawn task2) ``` ### Notes The spawned process cannot receive messages. If a task makes a long HTTP request or takes a long time, the runtime can pause it and switch to another task instead of blocking. ``` -------------------------------- ### Appendable Type Constraint Example Source: https://github.com/elm/core/blob/master/_autodocs/types.md Demonstrates the 'appendable' type constraint, applicable to types that support concatenation using the (++) operator, such as String and List. ```elm (++) : appendable -> appendable -> appendable ``` -------------------------------- ### Succeed Task Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/Task.md Creates a task that succeeds immediately with a given value. Often used with `andThen`. ```elm succeed 42 succeed [] succeed "hello" ``` ```elm -- With andThen timeInMillis : Task x Int timeInMillis = Time.now |> andThen (\t -> succeed (Time.posixToMillis t)) ``` -------------------------------- ### Function Composition and Piping Source: https://github.com/elm/core/blob/master/_autodocs/api-reference/Basics.md Utilities for composing and piping functions. ```APIDOC ## Function Composition and Piping ### Description Utilities for composing and piping functions. ### Functions - `(<<)` ((b -> c) -> (a -> b) -> (a -> c)): Left function composition - `(>>)` ((a -> b) -> (b -> c) -> (a -> c)): Right function composition - `(\|>)` (a -> (a -> b) -> b): Forward pipe - `(<\|)` ((a -> b) -> a -> b): Backward pipe - `identity` (a -> a): Identity function - `always` (a -> b -> a): Constant function ```