如何判断列表中是否有第三项? [英] How can I tell if a list has a third item?

查看:94
本文介绍了如何判断列表中是否有第三项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数接受一个包含两个或三个元素的列表.

I have a function that takes a list that either has two or three elements.

;; expecting either ((a b c) d) or ((a b c) d e)
(define (has-third-item ls)
      (if (null? (caddr ls))
          false
          true)
      )

但是此代码因

mcar: expects argument of type <mutable-pair>; given ()

在(null?(caddr ls))表达式上.

on the (null? (caddr ls)) expression.

我也尝试过

(eq? '() (caddr ls))

但是它也不起作用.我怎么知道是否还有第三项?

but it didn't work either. How do I tell if there's a third item or not?

推荐答案

您不想要caddr,想要(if(null?(cddr ls))...或仅使用length来查找列表的长度,然后将其与您感兴趣的值进行比较.

You don't want caddr, you want (if (null? (cddr ls)) ... Or just use length to find the length of the list, and compare it to the value you're interested in.

终止列表的'()始终位于一对的cdr位置,因此,在汽车位置(cad + r会这样做)寻找它不会产生效果.

The '() that terminates a list will always be in the cdr position of a pair, so looking for it in the car position (which cad+r will do) isn't going to be productive.

这篇关于如何判断列表中是否有第三项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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