list - Breaking a number into groups of threes in Scheme -


i trying create function takes in number , breaks groups of 3 : (group-of-three 12345) -> '(12 345)

this code i've been working on:

(define (group-of-three n)   (cond ((< n 1000) n))   (cond ((> n 1000)           (cons (group-of-three (quotient n 1000)) (remainder n 1000))))) 

and when call (group-of-three 9999) '(# . 999)

any appreciated, i'm new scheme i'm sure solution pretty easy , i'm not seeing it.

there couple of problems code:

  • cond being used incorrectly, single cond required, 2 mutually exclusive conditions. or simpler, use if expression
  • the base case of recursion wrong, remember: we're building list, result must end empty list
  • to output list in right order, input number ought processed right-to-left. easier if use helper procedure parameter accumulating results - incidentally, produce tail-recursive solution. alternatively, use named let

this mean:

(define (group-of-three n)   (helper n '()))  (define (helper n acc)   (cond ((< n 1000) (cons n acc))         (else (helper (quotient n 1000)                       (cons (remainder n 1000) acc))))) 

it works expected:

(group-of-three 12345) => '(12 345)  (group-of-three 12345678) => '(12 345 678) 

Comments

Popular posts from this blog

python - Subclassed QStyledItemDelegate ignores Stylesheet -

java - HttpClient 3.1 Connection pooling vs HttpClient 4.3.2 -

SQL: Divide the sum of values in one table with the count of rows in another -