-
In the http request I want to cast the text argument of token ID into a Nat. Anyone know how to do that cast? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
I don't know if there's a built in way to do this, quick search I couldn't find a toNat from Text. But you could make a function, that takes a string, for loops through its characters, pass it through a switch that matches the character with a 0-9 character, and then build out the number, multiplying the previous number by 10 and adding the new number: |
Beta Was this translation helpful? Give feedback.
-
This is one way to do it. I meant to post this after the bootcamp but I forgot. Using a fold probably isn’t the most efficient way but does the job. import Char "mo:base/Char";
import Debug "mo:base/Debug";
import Iter "mo:base/Iter";
import List "mo:base/List";
import Nat "mo:base/Nat";
import Nat32 "mo:base/Nat32";
import Option "mo:base/Option";
import Text "mo:base/Text";
func charToNat(char : Char) : ?Nat {
if (Char.isDigit(char)) {
?(Nat32.toNat(Char.toNat32(char) -% Char.toNat32('0')))
} else {
null
}
};
func parseNat(text : Text) : ?Nat {
let chars = Iter.toList<Char>(Text.toIter(text));
type State = {
power : Nat;
value : Nat;
};
let initialState : State = {
power = 0;
value = 0;
};
let finalState : ?State = List.foldRight<Char, ?State>(chars, ?initialState, func (char, state) {
return do ? {
let power = state!.power;
let value = state!.value;
let nat = charToNat(char)!;
{
power = power + 1;
value = value + (nat * (10 ** power));
}
};
});
return Option.map<State, Nat>(finalState, func (x) {
x.value
});
};
Debug.print(debug_show(parseNat("0123456789"))); |
Beta Was this translation helpful? Give feedback.
I don't know if there's a built in way to do this, quick search I couldn't find a toNat from Text. But you could make a function, that takes a string, for loops through its characters, pass it through a switch that matches the character with a 0-9 character, and then build out the number, multiplying the previous number by 10 and adding the new number:
"1357"
'1' -> (0 * 10) + 1
'3' -> (1 * 10) + 3
'5' ->(13 * 10) + 5
'7' -> (135 * 10) + 7
1357