Functional programming 在列表方案中的位置

Functional programming 在列表方案中的位置,functional-programming,scheme,Functional Programming,Scheme,我不知道如何做到这一点,也找不到任何地方的例子。如何在列表中找到值的位置。例如,我有一个(定义findValue x lst),它接受一个值和一个列表,我想从该列表中键入(findValue 3'(1 2 0 8 5 6)),它应该返回0,因为位置3中的值是0。根据我的理解,通常情况下,位置3在数组中至少是8而不是0。在这里它是如何工作的,我如何处理这个问题 谢谢 试试看: (define (at n xs) (cond ((null? xs) xs) ((= n 1

我不知道如何做到这一点,也找不到任何地方的例子。如何在列表中找到值的位置。例如,我有一个
(定义findValue x lst)
,它接受一个值和一个列表,我想从该列表中键入
(findValue 3'(1 2 0 8 5 6))
,它应该返回0,因为位置3中的值是0。根据我的理解,通常情况下,位置3在数组中至少是8而不是0。在这里它是如何工作的,我如何处理这个问题

谢谢

试试看:

(define (at n xs)
    (cond ((null? xs) xs)
          ((= n 1) (car xs))
          (else (at (- n 1) (cdr xs)))))
按如下方式使用:

(at 3 '(1 2 0 8 5 6)) => 0
(define (curry func . args)
    (lambda x (apply func (append args x))))

(define (flip func)
    (lambda (a b) (func b a)))
(define position (curry (flip at) '(1 2 0 8 5 6)))
(position 3) => 0
(position 4) => 8
对于基于零的索引,将第三行的
(=n1)
检查更改为
(=n0)

编辑:那么您想部分应用
at
功能吗?你只需要
咖喱
翻转
。它们的定义如下:

(at 3 '(1 2 0 8 5 6)) => 0
(define (curry func . args)
    (lambda x (apply func (append args x))))

(define (flip func)
    (lambda (a b) (func b a)))
(define position (curry (flip at) '(1 2 0 8 5 6)))
(position 3) => 0
(position 4) => 8
使用
curry
flip
您现在可以在部分应用
,如下所示:

(at 3 '(1 2 0 8 5 6)) => 0
(define (curry func . args)
    (lambda x (apply func (append args x))))

(define (flip func)
    (lambda (a b) (func b a)))
(define position (curry (flip at) '(1 2 0 8 5 6)))
(position 3) => 0
(position 4) => 8
您现在可以使用
位置
,如下所示:

(at 3 '(1 2 0 8 5 6)) => 0
(define (curry func . args)
    (lambda x (apply func (append args x))))

(define (flip func)
    (lambda (a b) (func b a)))
(define position (curry (flip at) '(1 2 0 8 5 6)))
(position 3) => 0
(position 4) => 8

希望对您有所帮助。

通常索引是从
0
开始计算的,您的理解是正确的。但是,如果需要实现一个从
1
开始计算索引的
findValue
过程,那么编写该过程并不难:

(define (findValue idx lst)
  (cond ((or (null? lst) (negative? idx)) #f)
        ((= idx 1) (car lst))
        (else (findValue (sub1 idx) (cdr lst)))))
说明:

  • 如果作为参数接收的列表为空或索引为负数,我们将其视为特殊情况,并返回
    #f
    ,以指示未找到该值
  • 如果索引是
    1
    ,那么我们就在我们想要的地方,所以是时候返回当前元素了
  • 否则,推进递归:从索引中减去一个,并在列表上前进一个位置
它按预期工作:

(findValue  3 '(1 2 0 8 5 6))
=> 0
(findValue -1 '(1 2 0 8 5 6))
=> #f
(findValue  7 '(1 2 0 8 5 6))
=> #f

谢谢现在更有意义了,我没有意识到n控制着索引。好吧,如果你比我更了解这一点,我不妨问问你。我试着把它放到一个函数中,它返回一个函数类型的东西。例如,调用
(位置3)
将返回与原始问题相同的结果。我理解返回另一个函数的简单函数,但是我不能很容易地理解这个函数。我已经更新了我的答案。这就是你想要做的吗?是的,你是对的,我几天前就知道了,它只是简单地添加了lambda,并在其中有另一个函数。谢谢那么基本上你是在强制索引从1开始?所以如果我把
(=idx2))
放在2开始索引?从来没有对其他任何东西这样做过,所以这是不同的。@user2318083是的,在某种程度上,我们声明索引
1
是我们要开始计数的地方。注意,在我们到达所需索引之前,您还必须考虑列表为空的情况,或者如果索引为负的情况。