Unable to convert strings to integers inside closure
markjreed opened this issue ยท comments
Tried to create a simple comparator to use with ๐ฆ to sort a list of numeric strings in reverse order:
๐a๐กb๐กโก๏ธ ๐ข
โฉ๏ธ ๐ขb 10โ๏ธโ ๐ขa 10โ๏ธ
๐ โก๏ธ rev
But the compiler complains that " ๐ฌs๐ข does not provide methods.". Where did that ๐ฌ come from?
Assuming that meant they'd been wrapped into Optionals somehow, I tried to unwrap them with ๐บ, but got "๐บ can only be used with optionals or error-prone calls."
Not sure what's going on here.
Hey @markjreed , I took a look at your code and the documentation and I think I know what is going on here.
According to the documentation, calling ๐ขโ๏ธreturns a ๐ฌ๐ข, which means an optional of type number. You can read more about it in the guide on optionals, but essentially this protects the program against the possibility of an invalid value being passed into the function, for example the string ๐คsldkfjsldkj๐ค
cannot be parsed as a ๐ข. So after parsing you can compare the result to No Value (๐คท) then if it's not that you can use the ๐บ operator to unwrap the optional (๐ฌ) to a ๐ข. Does that make sense?
The only other alternative would be to make the function error-prone and just use the ๐บ without checking, but I'm not sure you would want to go that route for this example.
Thanks for using Emojicode!
Here is a full working example:
๐ ๐
๐a๐กb๐กโก๏ธ ๐ข
๐ขa 10โ โก๏ธ aInt?
๐ขb 10โ โก๏ธ bInt?
โช๏ธ aInt? ๐ ๐คท ๐ค bInt? ๐ ๐คท ๐
๐ญ They are both invalid, treat them as the same
โฉ๏ธ 0
๐ ๐
โช๏ธ aInt? ๐ ๐คท ๐
๐ญ a is invalid, put b first
โฉ๏ธ 1
๐ ๐
โช๏ธ bInt? ๐ ๐คท ๐
๐ญ b is invalid, put a first
โฉ๏ธ -1
๐ ๐
๐
โฉ๏ธ ๐บbInt? โ ๐บaInt?
๐
๐ โก๏ธ rev
๐ฟ
๐ค123๐ค
๐ค321๐ค
๐คasdf๐ค
๐ โก๏ธ ๐๏ธ๐list
๐ฆlist revโ
๐ item list ๐
๐itemโ
๐
๐
The output is:
321
123
asdf
Personal style note: I like to use the ?
character in my variable names when I know they are going to be optionals. That way I remember to unwrap them or handle them properly. Since Emojicode will allow pretty much any non-emoji character (excluding whitespace) in variable names, it works pretty well for me.
Another approach would be to use ๐ญโ and ๐ฐโto no longer have to deal with conversion from string to int in the sorting function:
๐ ๐
๐ฟ
๐ค123๐ค
๐ค321๐ค
๐คasdf๐ค
๐ โก๏ธ list
๐ a๐ก โก๏ธ ๐
๐ขa 10โ โก๏ธ aInt?
โฉ๏ธ โaInt? ๐ ๐คทโ
๐ โก๏ธ filterOutInvalidIntStrings
๐ญlist filterOutInvalidIntStringsโ โก๏ธ onlyIntStrings
๐ a๐ก โก๏ธ ๐ข
๐ขa 10โ โก๏ธ aInt?
โฉ๏ธ ๐บaInt?
๐ โก๏ธ convertToInt
๐ฐonlyIntStrings convertToIntโ โก๏ธ ๐๏ธ๐ints
๐a๐ขb๐ขโก๏ธ ๐ข
โฉ๏ธ b โ a
๐ โก๏ธ rev
๐ฆints revโ
๐ item ints ๐
๐๐ค๐งฒitem๐งฒ๐คโ
๐
๐
The output is:
321
123
Oh, of course. It was complaining about ๐ฌ๐ข, not ๐ฌ๐ก, so it was the result of the ๐ข calls that needed unwrapping, not the parameters. D'oh! Thanks for the help!