简体   繁体   English

在列表方案中的位置

[英]Position in list scheme

I'm not sure how to do this and couldn't find an example of it anywhere. 我不确定如何执行此操作,因此无法在任何地方找到它的示例。 How do I find the position of a value in a list. 如何在列表中找到值的位置。 For example I have a (define findValue x lst) which accepts a value and list and from that list I want type in (findValue 3 '(1 2 0 8 5 6)) and it should return 0 since the value in position 3 is 0. From my understanding and how it usually is position 3 would be 8 and not 0 in arrays at least. 例如,我有一个(define findValue x lst) ,它接受一个值和列表,然后从该列表中我要输入(findValue 3 '(1 2 0 8 5 6))并且由于位置3的值是0。据我了解,位置3通常如何,至少在数组中为8,而不是0。 How does it work in here and how do I approach this problem? 它在这里如何工作,以及如何解决这个问题?

Thanks! 谢谢!

Try: 尝试:

(define (at n xs)
    (cond ((null? xs) xs)
          ((= n 1) (car xs))
          (else (at (- n 1) (cdr xs)))))

Use it as follows: 如下使用它:

(at 3 '(1 2 0 8 5 6)) => 0

For zero-based indexing change the (= n 1) check on the 3rd line to (= n 0) . 对于基于零的索引,将第三行上的(= n 1)检查更改为(= n 0)

Edit: So you want to partially apply the at function? 编辑:所以您想部分应用at函数? All you need is curry and flip . 您需要的只是curryflip They are defined as follows: 它们的定义如下:

(define (curry func . args)
    (lambda x (apply func (append args x))))

(define (flip func)
    (lambda (a b) (func b a)))

Using curry and flip you can now partially apply at as follows: 现在,您可以使用curry and flip进行部分申请at如下所示:

(define position (curry (flip at) '(1 2 0 8 5 6)))

You can now use position as follows: 您现在可以按以下方式使用position

(position 3) => 0
(position 4) => 8

Hope that helped. 希望能有所帮助。

Usually indexes are counted starting from 0 , and your understanding is correct. 通常,索引从0开始计数,您的理解是正确的。 But if you're required to implement a findValue procedure that starts counting indexes from 1 , it's not that hard to write the procedure: 但是,如果您需要实现一个从1开始对索引进行计数的findValue过程,则编写该过程并不难:

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

Explanation: 说明:

  • If the list received as parameter is empty or the index becomes negative, we treat that as a special case and return #f to indicate that the value was not found 如果作为参数接收的列表为空或索引变为负数,则将其视为特殊情况,并返回#f表示未找到该值
  • If the index is 1 then we're right where we wanted, so it's time to return the current element 如果索引为1那么我们就在我们想要的位置,所以现在该返回当前元素了
  • Otherwise advance the recursion: subtract one from the index and advance one position over the list 否则,递归递归:从索引中减去1并在列表中提前一个位置

It works as expected: 它按预期工作:

(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

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

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