大学工作 - 计划

时间:2016-10-11 08:16:36

标签: scheme racket

所以我正在阅读我的编程语言模块的一些过去的论文,我遇到了这个问题,我不知道如何去做。

问:“定义一个反向计数的Scheme函数,它需要两个 列表,其中第二个是非负整数列表 与第一个列表相同的长度,并返回一个元素列表 第一个列表,以相反的顺序,每个重复多次 由第二个列表的相应元素指定。“

示例:

(reverse-with-count '(a b c) '(1 2 3)) => (c c c b b a)
(reverse-with-count '(d c b a) '(3 0 0 1)) => (a d d d)

谢谢:)

编辑:

(define (repeat n s)
  (if (= n 0)
      '()
      (append s
              (repeat (- n 1) s))))

使用:

 (repeat 10 '(test)) => '(test test test test test test test test test test)

3 个答案:

答案 0 :(得分:2)

我认为这应该有效:

(define (multi-element element n)
  (map (lambda (x) element) (range n)))

(define (range-list xs ys)
  (map (lambda (x y) (multi-element x y)) xs ys))

(define (reverse-with-count xs ys)
  (reverse (flatten (range-list xs ys))))

输出:

> (reverse-with-count '(a b c) '(1 2 3))
(c c c b b a)
> (reverse-with-count '(d c b a) '(3 0 0 1))
(a d d d)
> (reverse-with-count '(x baz y z bar g t foo) '(0 1 0 0 1 0 0 1))
(foo bar baz)

答案 1 :(得分:0)

基于累加器的方法在这里很有效:

(define (repeat n s (result '()))
  (if (positive? n)
      (repeat (- n 1) s (cons s result))
      result))

使用或不使用初始值result

> (repeat 10 'a)
'(a a a a a a a a a a)
> (repeat 10 'a '(initial))
'(a a a a a a a a a a initial)

然后以相同的方式进行第二个程序:

(define (reverse-with-count elts cnts (result '()))
  (if (or (null? elts) (null? cnts))
      result
      (reverse-with-count (cdr elts)
                          (cdr cnts)
                          (repeat (car cnts) (car elts) result))))

测试:

> (reverse-with-count '(a b c) '(1 2 3)) 
'(c c c b b a)
> (reverse-with-count '(a b c) '(1 2 3))
'(c c c b b a)
> (reverse-with-count '(d c b a) '(3 0 0 1))
'(a d d d)
> (reverse-with-count '(x baz y z bar g t foo) '(0 1 0 0 1 0 0 1))
'(foo bar baz)

答案 2 :(得分:0)

以下版本使用/ list两次创建列表列表,然后展平并反转:

var sql = require('mssql');
var dbConfig = {};
var Connection = new sql.Connection(dbConfig);
Connection.connect().then(function(_connection){
    var request = new sql.Request(_connection);
    request.verbose = true;
    request.input('username', 'patriksimek');
    request.input('password', 'delete from dbo.Users where userId =1');
    request.input('attempts', 2);
    request.execute('my_stored_procedure');
})

还可以使用一般的,高度灵活的,名为let'循环方法。不需要逆转,因为' cons'产生一个反向清单:

(define (f l k)
  (reverse
   (flatten
    (for/list ((i k)(n (length k)))
      (for/list ((x i))
        (list-ref l n))))))