Python lets you use the asterisk operator to repeat a character or string a given number of times:
>>> 'abc' * 7
'abcabcabcabcabcabcabc'
Is something like this possible in Motoko?
I tried to achieve the effect by combining Array.init and Array.fold as follows, but am running into issues with array mutability. Here’s my attempt. I’m hoping someone can correct this code to avoid the mutability issues, but also point me toward a better way to repeat a string in Motoko.
func fold(accum: Text, el: Text): Text {
accum # el;
};
let arr: [Text] = Array.init(7, "abc");
let indent = Array.foldLeft<Text, Text>(arr, "", fold);
I got type error, cannot infer type of wildcard with your code, @rossberg. Adding the type to the tabulate call works. Not sure why that couldn’t be inferred from the function’s return type. I also had to import Text, which I guess is necessary when using functions like concat but not when using using the Text type
import Text "mo:base/Text";
let arr = Array.tabulate<Text>(7, func _ { "abc" });
let indent = Array.foldLeft(arr, "", Text.concat);
Ah, yes, sorry. For the call of a generic function, the type checker can only propagate types in one direction, either inside out or outside in. That means that you either need to provide all type arguments explicitly (so that all the values’ argument types can be inferred), or all value arguments need to be explicitly typed (so that the type arguments can be inferred). That means that either of the following would work:
I know that C# went to quite some lengths to get this to work, leading to a very complicated inference algorithm based on solving constraints in dependency order that we don’t want to commit to.