I am designing a function that consumes a natural number (like 0, 1, 2, ….etc) and returns the string representing it in unary (base 1) using the symbol I and also displaying the number in decimal after its unary form. So if I type in 2, I would get "II (2)". 5, I would get "IIIII (5)" .
I’ve done it this way:
(define (number->unary c )
(cond
[(= c 1 ) "I (1)" ]
[(= c 2 ) "II (2)" ]
[(= c 3) "III (3)"]
[(= c 4) "IIII (4)"]
[(= c 5) "IIIII (5)"]
[(= c 6) "IIIIII (6)"]
[(= c 7) "IIIIIII (7)"]
[(= c 8) "IIIIIIII (8)"]
[(= c 9) "IIIIIIIII (9)"]
[(= c 10) "IIIIIIIIII (10)"]))
but is there an easier way to do this problem? I’ve been reading about number->string, string-appends, and replicates but I am not sure where to start.
There’s an easier way indeed – using a loop for generating the appropriate number of
"I"characters. Think of it, what would happen ifcequals100? you shouldn’t have to create a hundred conditions for this!Here’s one possible way, using a helper procedure for implementing iteration with a recursive procedure called
loop: