Friday 15 February 2013

racket - scheme how do you sum numbers in a list when you have structures and list of lists -



racket - scheme how do you sum numbers in a list when you have structures and list of lists -

;; atom 1 of: ;; -- symbol ;; -- string ;; -- number ;; sexp (s-expression) 1 of: ;; -- empty ;; -- (cons atom sexp) ;; -- (cons sexp sexp)

so i'm trying sum numbers in sexp! here's code,

;; sum-numbers: sexp -> number (define (sum-numbers sexp) (cond [(empty? sexp) 0] [(atom? (first sexp)) (+ (atom-sum-numbers (first sexp)) (sum-numbers (rest sexp)))] [(sexp? (first sexp)) (+ (sum-numbers (first sexp)) (sum-numbers (rest sexp)))])) ;; atom-sum-numbers: atom -> number (define (atom-sum-numbers a) (cond [(symbol? a) 0] [(number? a) (+ (atom-number a) (atom-sum-numbers a))] [(string? a) 0]))

however, error says cond: question results false. i'm wondering happened there.

you're mixing struct accessor procedures list manipulation procedures, won't work - have consistent, if using structs must utilize struct's own procedures.

also, atom construction looks wrong, is, it's saying: atom made of symbol, string and number (the 3 things, not 1 of them!). of course, symbol?, number? , string? predicates won't work struct, that's why cond complaining of conditions false.

i suggest seek else, atoms atoms, not structs. otherwise you'll have rethink atom structure, in current form won't work in way imagine. instance, work:

(define (sum-numbers sexp) (cond [(empty? sexp) 0] [(sexp? (sexp-atom sexp)) (+ (sum-numbers (sexp-atom sexp)) (sum-numbers (sexp-sexp sexp)))] [else (+ (atom-sum-numbers (sexp-atom sexp)) (sum-numbers (sexp-sexp sexp)))])) (define (atom-sum-numbers a) (cond [(symbol? a) 0] [(number? a) a] [(string? a) 0]))

let's test it, , notice how atoms plain scheme atoms, not instances of atom struct:

(sum-numbers (make-sexp 'x (make-sexp 7 (make-sexp "a" '())))) => 7

scheme racket

No comments:

Post a Comment