Skip to content

std::parse

Reading values from text. Parse is the interface of a type read from one text, such as a path segment: Int.parse("42"), Uuid.parse(text). A type of the program’s own implements it to be read the same way; a distinct type over one of these reads its inner type:

import
    std::parse.Parse
    std::uuid.{self, Uuid}
end

type UserId Uuid

impl Parse<uuid.Error> for UserId
    fn parse(text: String) -> Result<UserId, uuid.Error>
        Uuid.parse(text) |> Result.map(UserId)
    end
end

ParseFields reads several named texts at once, into Unit or into an anonymous struct whose fields each implement Parse and Display, as std::http’s typed routes read their path parameters.

Import with import std::parse.

Interfaces

interface Parse<E>
    fn parse(text: String) -> Result<self, E>
end

A type read from one text. E is why a text is not one, chosen by the impl: String reads every text and cannot fail, so its E is Infallible.

assert Int.parse("42") == Ok(42)
assert Int.parse("4x") == Err("`4x` is not a whole number")
assert String.parse("a b") == Ok("a b")
fn parse(text: String) -> Result<self, E>

interface Parse

interface ParseFields
    fn field_names() -> List<String>
    fn parse_fields(texts: List<String>) -> Maybe<self>
    fn field_texts(fields: self) -> List<String>
end

Several named texts read at once: Unit, which has none, or an anonymous struct whose fields each implement Parse and Display, such as {id: Uuid, page: Int}. The compiler supplies an anonymous struct’s functions; no other type implements it. Each list is in the order field_names gives, which is the fields’ names in order. read_fields and write_fields are the functions to call.

fn field_names() -> List<String>

interface ParseFields

The names of the fields.

fn parse_fields(texts: List<String>) -> Maybe<self>

interface ParseFields

The value whose fields are read from texts, one per field, each with its type’s parse, or None when one does not parse.

fn field_texts(fields: self) -> List<String>

interface ParseFields

Each field’s Display text.

fn read_fields<P>(texts: Map<String, String>) -> Maybe<P> where P: ParseFields

The P whose fields are read from texts by name, or None when a field’s text is missing or does not parse.

texts = {"id" => "7", "name" => "ann"}
assert read_fields(texts) == Some({id: 7, name: "ann"})
assert read_fields<{id: Int}>({"id" => "x"}) == None
assert read_fields<{id: Int}>({"name" => "x"}) == None
fn write_fields<P>(fields: P) -> List<(String, String)> where P: ParseFields

Each field of fields with its name and its Display text, in name order.

assert write_fields({id: 7, name: "ann"}) == [("id", "7"), ("name", "ann")]