Function number

  • Parse a bunch of different kinds of numbers without backtracking.

    Remarks

    Example

    A parser for Elm would need to handle integers, floats, and hexadecimal like this:

        type Number = IntE | FloatE;

    class IntE {
    constructor(public readonly value: number) {}
    }

    class FloatE {
    constructor(public readonly value: number) {}
    }
    const elmNumber: P.Parser<Number> = P.number({
    int: (n) => new IntE(n),
    hex: (n) => new IntE(n), // 0x001A is allowed
    float: (n) => new FloatE(n),
    });

    Example

    Float

    If you wanted to implement the float parser, it would be like this:

        const float: Parser<number> =
    number({
    int: (n) => n,
    float: (n) => n
    });

    Notice that it actually is processing int results! This is because 123 looks like an integer to me, but maybe it looks like a float to you. If you had int : undefiend, floats would need a decimal like 1.0 in every case. If you like explicitness, that may actually be preferable!

    Note: This function does not check for weird trailing characters in the current implementation, so parsing 123abc can succeed up to 123 and then move on. This is helpful for people who want to parse things like 40px or 3m, but it requires a bit of extra code to rule out trailing characters in other cases.

    Type Parameters

    • A

    Parameters

    • args: {
          binary?: ((n: number) => A);
          float?: ((n: number) => A);
          hex?: ((n: number) => A);
          int?: ((n: number) => A);
          octal?: ((n: number) => A);
      }
      • Optional binary?: ((n: number) => A)
          • (n: number): A
          • Parameters

            • n: number

            Returns A

      • Optional float?: ((n: number) => A)
          • (n: number): A
          • Parameters

            • n: number

            Returns A

      • Optional hex?: ((n: number) => A)
          • (n: number): A
          • Parameters

            • n: number

            Returns A

      • Optional int?: ((n: number) => A)
          • (n: number): A
          • Parameters

            • n: number

            Returns A

      • Optional octal?: ((n: number) => A)
          • (n: number): A
          • Parameters

            • n: number

            Returns A

    Returns Simple.Parser<A>