Thread: Scheme function

    #1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2004
    Location
    Canada
    Posts
    242
    Rep Power
    0

    Scheme function


    How can I use foldl to write a function for the running totals of a list, i.e.

    (total (list 1 1 1)) => (list 1 2 3)

    Any hints?
  2. #2
  3. Hello World :)
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2003
    Location
    Hull, UK
    Posts
    2,537
    Rep Power
    69
    Hey Net,

    This should do the job; I haven't really tested it as I'm on windows and don't have Scheme installed.

    Code:
    (define (total lst)
      (reverse
       (foldr (lambda (a b)
                (cons (if (null? b)
                          a
                          (+ a (car b)))
                       b))
              ()
              lst)))
    Please let me know if you came up with something different .

    Take care,

    Mark.
    programming language development: www.netytan.com Hula

  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2006
    Posts
    247
    Rep Power
    82
    you mean
    Code:
    (define (total lst)
      (reverse
       (foldl (lambda (a b)
    	    (cons (if (null? a)
    		      b
    		      (+ b (car a)))
    		  a))
    	  '()
    	  lst)))
  6. #4
  7. Hello World :)
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2003
    Location
    Hull, UK
    Posts
    2,537
    Rep Power
    69
    Originally Posted by spoon!
    you mean
    Code:
    (define (total lst)
      (reverse
       (foldl (lambda (a b)
    	    (cons (if (null? a)
    		      b
    		      (+ b (car a)))
    		  a))
    	  '()
    	  lst)))
    Hi,

    I really did mean foldr - it is easy to mix the two functions up though. Please check out the fold page on wikipedia .

    http://en.wikipedia.org/wiki/Fold_%28higher-order_function%29

    Mark.
    programming language development: www.netytan.com Hula


IMN logo majestic logo threadwatch logo seochat tools logo