Hello i am trying to do a incFirst function in ML. The function does the following: incFirst "bad" = "cad" incFirst "shin" = "thin". This is what i try to do fun incFirst s = chr(ord s + 1) ^ substring(s, 1, size s -1);
I get the following error: Can't unify string (In Basis) with char (In Basis)
(Different type constructors)
Found near chr (ord s + 1) ^ substring (s, 1, ... - ...)
Exception- Fail "Static Errors" raised
Any idea how i can concatenate a char with a string if the "^" operator is not working?
Asked
Active
Viewed 1,454 times
0

Sebi Danila
- 21
- 3
1 Answers
0
The operator is working, it's just that you can only concatenate strings,
and that ord
operates on characters, not on strings.
(A character is not the same as a one-character string.)
You need to extract the first character and then convert the result to a string
fun incFirst s = String.str(chr (ord (String.sub (s,0)) + 1)) ^ substring(s, 1, size s - 1)
or you could take a detour through a list
fun incFirst s = let
fun inc (c::cs) = (chr(ord c + 1))::cs
in
implode (inc (explode s))
end

molbdnilo
- 64,751
- 3
- 43
- 82
-
2It would be better to use String.str here rather than Char.toString. Char.toString creates a printable version of a character which could involve expanding escapes. String.str always creates a single character string. – David Matthews Jan 10 '18 at 16:31
-
@DavidMatthews Thanks. – molbdnilo Jan 11 '18 at 07:43