【问题标题】:Product as input arguments?产品作为输入参数?
【发布时间】:2014-02-27 07:26:02
【问题描述】:

在lisp/scheme中,有没有使用set product作为函数输入的形式? map 形式对需要 n 个参数的函数使用 n 个长度相等的列表。有时,我们需要参数来自一组集合的乘积。例如:

(pmap (λ (d p) foo)
           A B)

这里,列表A可能与B有不同的长度,pmap馈送A乘积的每个元素strong> 和 Blambda 表达式。

表格for* 的方案/球拍可以完成这项工作:

(for* ([x '(0 2 4)]
       [y '(1 3 5)])
      ((λ (d p)
           (printf "(~a, ~a)\n" d p))
       x y))

输出:

(0, 1)
(0, 3)
(0, 5)
(2, 1)
(2, 3)
(2, 5)
(4, 1)
(4, 3)
(4, 5)

我想知道在 scheme 中是否存在类似于 ma​​pfold 的其他方式来做到这一点。

【问题讨论】:

    标签: scheme racket


    【解决方案1】:

    据我所知,标准中不存在这样的内容。然而,写一个不是问题。

    对于有用的列表函数的概述,我可以推荐 srfi1,它为您提供了除 map 和 fold 之外的许多有用的操作。

    http://srfi.schemers.org/srfi-1/srfi-1.html

    【讨论】:

      【解决方案2】:

      我编写了pmap 的以下实现。它仅使用 conscarcdrnull?applymapreverse 工作,并支持任意数量的参数,如 map

      (define (pmap f . xs) 
        (define (carry a xs ys then)
          (if (and (not (null? ys)) (null? (car ys)))
              '()
              (if (null? xs) 
                  (then (reverse a))
                  (if (null? (car xs))
                      (if (null? (cdr xs)) 
                          '()
                          (carry (cons (car ys) a) (cons (cdr (car (cdr xs))) (cdr (cdr xs))) (cdr ys) then))
                      (carry (cons (car xs) a) (cdr xs) (cdr ys) then)))))
      
        (define (pmap-helper f xs ys)
          (carry '() xs ys 
                 (lambda (xs)
                   (cons (apply f (map car xs)) 
                         (pmap-helper f (cons (cdr (car xs)) (cdr xs)) ys)))))
      
        (pmap-helper f xs xs))
      
      (display (pmap list '(0 2 4) '(1 3 5))) (newline)
      ;((0 1) (2 1) (4 1) (0 3) (2 3) (4 3) (0 5) (2 5) (4 5))
      

      唯一的区别是早期列表的迭代速度比后面的列表快,而您的示例正好相反。这个pmap 可以修改为:

      (define (pmap f . xs) 
        (define (carry a xs ys then)
          (if (and (not (null? ys)) (null? (car ys)))
              '()
              (if (null? xs) 
                  (then (reverse a))
                  (if (null? (car xs))
                      (if (null? (cdr xs)) 
                          '()
                          (carry (cons (car ys) a) (cons (cdr (car (cdr xs))) (cdr (cdr xs))) (cdr ys) then))
                      (carry (cons (car xs) a) (cdr xs) (cdr ys) then)))))
      
        (define (pmap-helper f xs ys)
          (carry '() xs ys 
                 (lambda (xs)
                   (cons (apply f (reverse (map car xs))) 
                         (pmap-helper f (cons (cdr (car xs)) (cdr xs)) ys)))))
      
        (let ((xs (reverse xs)))
          (pmap-helper f xs xs)))
      
      (display (pmap list '(0 2 4) '(1 3 5))) (newline)
      ; ((0 1) (0 3) (0 5) (2 1) (2 3) (2 5) (4 1) (4 3) (4 5))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-04-04
        • 1970-01-01
        • 2015-10-01
        • 1970-01-01
        相关资源
        最近更新 更多