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 ParseErrorThe integer that t writes, an optional - and one or more ASCII digits (spec/22 §4).
Parameters
t: the text
Returns
Int: the integer t writes, an optional - and one or more ASCII digits; space is not trimmed.
Fails with
Emptywhentis emptyNotADigitwhen a character is neither the leading-nor an ASCII digit;atis the scalar position, from 0, of the first oneNoDigitswhentis-aloneTooLongwhentis an optional-and more than 4300 ASCII digits, leading zeros included
Use instead
to_intwhen the reason does not matter
See also
Cost
Time O(b) (ADR 0070), where:
b: the length oftin UTF-8 bytes
Example
src/shop.una
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 1Specification
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.