Skip to content

Commit

Permalink
Solution to Lab 01 (#5)
Browse files Browse the repository at this point in the history
  • Loading branch information
nmheim authored Feb 23, 2024
1 parent 19a3689 commit 6e8f6e9
Showing 1 changed file with 11 additions and 11 deletions.
22 changes: 11 additions & 11 deletions labs/lab01.md
Original file line number Diff line number Diff line change
Expand Up @@ -130,16 +130,14 @@ The number of digits can be computed by successive dividing the input number by
the integer division, you can use the function `quotient`.
:::

<!--
::: details Solution
```scheme
(define (num-of-digits n [acc 1])
(cond [(< n 0) (num-of-digits (- n))]
[(< n 10) acc]
[else (num-of-digits (quotient n 10) (+ acc 1))]))
(define q (quotient n 10))
(if (= q 0) acc (num-of-digits q (+ acc 1))))
```
Thank you for the improved solution <u>@Denis Pak</u>!
:::
-->

### Task 2
Write a function `(num->str n [radix 10])` taking as input an integer `n` together
Expand All @@ -159,7 +157,6 @@ remainders. The remainder after integer division can be computed by the function
:::


<!--
::: details Solution
```scheme
(define (num->str n [radix 10])
Expand All @@ -174,18 +171,21 @@ remainders. The remainder after integer division can be computed by the function
rem-str
(string-append (num->str (quotient n radix) radix)
rem-str)))
```

; Alternative
#|
Alternatively, you can use `string-ref` to pick out the correct character from `numeric-alphabet`
given an index, and instead of `string-append`ing you can construct a list of characters which is
converted to a string in the end:
```scheme
(define numeric-alphabet "0123456789ABCDEF")
(define (num->char n [radix 10])
(string-ref numeric-alphabet (remainder n radix)))
(define (num->str n [radix 10] [acc '()])
(cond
[(negative? n) (num->str (- n) radix '(#\-))]
[(< n radix) (list->string (cons (num->char n radix) acc))]
[else (num->str (quotient n radix) radix (cons (num->char n radix) acc))]))
|#
```
:::-->

:::

0 comments on commit 6e8f6e9

Please sign in to comment.