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:
condbeing used incorrectly, singlecondrequired, 2 mutually exclusive conditions. or simpler, useifexpression- 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
Post a Comment