Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I tell if a list has a third item?

Tags:

lisp

scheme

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)
      )

But this code fails with

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

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

I also tried

(eq? '() (caddr ls))

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

like image 241
Kai Avatar asked Mar 19 '09 22:03

Kai


People also ask

How do you check if a value exists in a nested list?

Use the any() function to check if a value exists in a two-dimensional list, e.g. if any('value' in nested_list for nested_list in my_2d_list): . The any() function will return True if the value exists in the list and False otherwise.

How do you check if something is in a nested list Python?

You can use the built-in len() function to find how many items a nested sublist has.

How do I check if all elements are in a string?

Just use all() and check for types with isinstance() . @TekhenyGhemor - isinstance(item, str) and not item. lstrip('-'). isdigit() for zero or positive integers.

How do you check if two elements in a list are the same Python?

A straightforward way to check the equality of the two lists in Python is by using the equality == operator. When the equality == is used on the list type in Python, it returns True if the lists are equal and False if they are not.


1 Answers

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.

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.

like image 154
Jay Kominek Avatar answered Sep 22 '22 12:09

Jay Kominek