Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 Scheme- summing elements in a list within a structure
Index -> Programming, General Programming -> Functional Programming
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
rikachama




PostPosted: 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
Sponsor
sponsor
jcollins1991




PostPosted: 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




PostPosted: 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.
Display posts from previous:   
   Index -> Programming, General Programming -> Functional Programming
View previous topic Tell A FriendPrintable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 3 Posts ]
Jump to:   


Style:  
Search: