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?
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.
You can use the built-in len() function to find how many items a nested sublist has.
Just use all() and check for types with isinstance() . @TekhenyGhemor - isinstance(item, str) and not item. lstrip('-'). isdigit() for zero or positive integers.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With