Home / Docs / Standard library / Prelude

parse_int

Release v0.4.0Edition 0.2 and later

A function of the prelude, in scope in every module. Edition 0.2 and later.

una
pub parse_int(t: Text) -> Int
  fails ParseError

The integer that t writes, an optional - and one or more ASCII digits (spec/22 §4).

Parameters

Returns

Int: the integer t writes, an optional - and one or more ASCII digits; space is not trimmed.

Fails with

Use instead

See also

ParseError, trim, is_digits

Cost

Time O(b) (ADR 0070), where:

Example

src/shop.unauna
module shop

--- A stock adjustment typed by hand, and why it is not one. A sign is allowed, so `-3`
--- writes off three units.
adjustment(raw: Text) -> Text
=
  let outcome = attempt parse_int(raw)
  when outcome
    is Ok(n) -> "'{raw}': adjust the stock by {n}"
    is Err(failure) -> "'{raw}': {reason(failure)}"

reason(failure: ParseError) -> Text
=
  when failure
    is Empty -> "nothing typed"
    is NoDigits -> "a sign and no digits"
    is NotADigit(at) -> "not a digit at {at}"
    is TooLong -> "more digits than an integer may have"

pub main() -> Unit
  uses @console: Console[print]
=
  @console.print(adjustment("12"))
  @console.print(adjustment("-3"))
  @console.print(adjustment(""))
  @console.print(adjustment("-"))
  @console.print(adjustment("1x2"))

una run . prints:

Output
'12': adjust the stock by 12
'-3': adjust the stock by -3
'': nothing typed
'-': a sign and no digits
'1x2': not a digit at 1

Specification

Generated from the standard modules of una v0.4.0 (docs/std/listing.json, which is not part of the specification). The specification governs: spec/14 §1.