如何在列表中找到原子的位置 [英] How to find the position of an atom in list

查看:70
本文介绍了如何在列表中找到原子的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试查找原子在列表中的位置.

I am trying to find the position of an atom in the list.

(position-in-list 'a (a b c d e)) 给出0

(position-in-list 'b (a b c d e) ) 给出1

(position-in-list 'Z(a b c d e) ) 给出零.

我粘贴了仅返回1的代码.

I have pasted my code which only returns 1.

(defun position-in-list (letter list) )
( cond
( (null list) nil
)
( (eq (car list) letter) count 
)
( t (position-in-list letter (cdr list)) count)
)
)

( defun count ()
( + 0 1)
)

推荐答案

这里是仅使用递归的另一种解决方案:

Here is another solution using only recursion:

(defun position-in-list (letter liste)
   (cond
      ((atom liste) nil)
      ((equal letter (car liste)) 0)
      ((position-in-list letter (cdr liste)) (+ 1 (position-in-list letter (cdr liste)))) ) )

((atom liste) nil) =在所有响应之后,如果列表为空,则返回nil

((atom liste) nil) = after all the recusion, if the list is empty, it returns nil

((equal letter (car liste)) 0) =如果找到我们要查找的字母,则返回0并开始堆积

((equal letter (car liste)) 0) = if it finds the letter we are looking for, it returns 0 and starts unstacking

((position-in-list letter (cdr liste)) (+ 1 (position-in-list letter (cdr liste)))) =仅在尚未遍历整个列表的情况下才添加+1,因此仅当我们在此之前找到我们的字母时

((position-in-list letter (cdr liste)) (+ 1 (position-in-list letter (cdr liste)))) = it adds +1 only if have not gone through the whole list already, so only if we have found our letter before then

这篇关于如何在列表中找到原子的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆