Scheme- summing elements in a list within a structure
Author |
Message |
rikachama
|
Posted: Sun Nov 14, 2010 11:51 am Post subject: Scheme- summing elements in a list within a structure |
|
|
I know how to add up all the elements in the list, however I am trying to add up all the elements of a list that is in a structure but i keep getting errors.
-This would just be for adding the elements of a list byitself.
Scheme: | (define (sum k)
(cond
[(empty? k) 0]
[else (+ (first k) (sum (rest k)))]))
|
However, say I have a sturcture such as:
(define-struct struct1 (x y))
;;(make-struct1 "hello" (list 1 2 3 4 5))
with "hello" being x, and the list being y.
Scheme: | (define (sum k)
(cond
[(empty? (struct1-y k)) 0]
[else
(+ (first (struct1-y k)) (sum (rest (struct1-y k))))]))
|
I am selecting the list from the structure, yet I get the error struct1-y: expects argument of type <struct:struct1>; given (list 2 3 4 5) |
|
|
|
|
|
Sponsor Sponsor
|
|
|
jcollins1991
|
Posted: Sun Nov 14, 2010 12:37 pm Post subject: Re: Scheme- summing elements in a list within a structure |
|
|
Because after the first iteration you're passing your function a list instead of a structure, if you want to continue using your structure you have to change your function call to create a new structure instead:
code: |
(sum (make-struct1 (struct1-x k) (rest (struct1-y k))))
|
Otherwise, you could just use a wrapper function that extracts the list from the structure. Final option (though if this is for school work you probably can't use it yet) is to use foldr and do everything with 2 lines of code:
code: |
(define (sum k)
(foldr (lambda (x y) (+ x y)) 0 (struct1-y k)))
|
|
|
|
|
|
|
rikachama
|
Posted: Sun Nov 14, 2010 12:50 pm Post subject: Re: Scheme- summing elements in a list within a structure |
|
|
Thanks >< it makes sense now, but yeah I don't think I can use the 2nd solution. Thread can be closed now. |
|
|
|
|
|
|
|