1

I need to apply a function to all elements but the last one in a list. Basically I am writing a kind of toy compiler, so given a arithmetic term like this:

   (+ 1 10)

I would like to get something like

  Plus(1, 10)

I managed to get the following:

  Plus(1, 10 ,)

By using the map function:

(string-append "Plus ("   
                         (fold-right string-append ""  
                             (map (lambda (x) (string-append x ",")) (map compile-term (cdr t)))))    

where compile-term is the function I am writing and t is the term I compile.

So my question is the following, is there a clean way to apply a function to all elements but the last one of a list using Guile Scheme? Or the only solution it would be to use loops as indicated here.

Thanks a lot in advance.

pafede2
  • 1,626
  • 4
  • 23
  • 40

1 Answers1

2

I would use format for this kind of cases. The following tested* code (thanks @Chris Jester-Young) might do what you need:

(format #f "~a(~{~a~^, ~})" (compile-term (car seq))
                            (map compile-term (cdr seq)))

When you have a state, you might prefer to use fold-*. Your string-append could be replaced by an anonymous function that calls string-append on the compile terms, and skip the comma when called with the initial value of fold.

coredump
  • 37,664
  • 5
  • 43
  • 77