Try it online!
Finding a half-decent layout for this was quite tricky. I'm still not super happy with it because of the spaces, the
< and the
;, but this is the best I could do for now.
String length is one of those very common built-ins that doesn't exist in Alice, because its input is a string and its output is an integer (and all Alice commands are strictly integers to integer or strings to strings). We can measure a string's length by writing it to the tape in Ordinal mode and then finding its end in Cardinal mode.
/ Reflect to SE. Switch to Ordinal. While in Ordinal mode, the IP will bounce
diagonally up and down through the code.
! Store an implicit empty string on the tape, does nothing.
; Discard an implicit empty string, does nothing.
i Read all input as a string.
'- Push "-".
< Set the horizontal component of the IP's direction to west, so we're bouncing
- Remove substring. This deletes the minus sign if it exists.
'i Push "i".
; Discard it again.
! Store the input, minus a potential minus sign, on the tape.
/ Reflect to W. Switch to Cardinal. The IP immediately wraps to the
e) Search the tape to the right for a -1, which will be found at the end
of the string we stored there.
< Does nothing.
q Push the tape head's position, which is equal to the string length.
'<sp> Push " ".
; Discard it again.
/ Reflect to NW. Switch to Ordinal. The IP immediately bounces off
the top boundary to move SW instead.
o Implicitly convert the string length to a string and print it.
IP bounces off the bottom left corner, moves back NE.
/ Reflect to S. Switch to Cardinal.
! Store an implicit 0 on the tape, irrelevant.
The IP wraps back to the first line.
/ Reflect to NE. Switch to Ordinal. The IP immediately bounces off
the top boundary to move SE instead.
@ Terminate the program.
I also tried taking care of the minus sign in Cardinal mode with
H (absolute value), but the additional mode switch always ended up being more expensive in my attempts.