简体   繁体   English

方案指南:将功能全部应用到最后一项

[英]Scheme Guile: apply function all ellements but last one

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. 其中compile-term是我正在编写的函数,而t是我正在编译的术语。

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? 所以我的问题是,是否有一种干净的方法将函数应用到除Guile Scheme列表中的最后一个元素之外的所有元素上? Or the only solution it would be to use loops as indicated here . 或唯一的解决方案是使用此处所示的循环。

Thanks a lot in advance. 非常感谢。

I would use format for this kind of cases. 我将在这种情况下使用format The following tested* code (thanks @Chris Jester-Young) might do what you need: 以下经过测试的代码(感谢@Chris Jester-Young)可能会满足您的需要:

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

When you have a state, you might prefer to use fold-* . 处于状态时,您可能更喜欢使用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 . 您的string-append可以由匿名函数代替,该匿名函数在编译条件下调用string-append ,并在使用fold的初始值调用时跳过逗号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM