Maxima: lambdas and sublist_indices behaving strangely when acting on symbols
Subject: Maxima: lambdas and sublist_indices behaving strangely when acting on symbols
From: Robert Dodier
Date: Mon, 14 May 2012 14:20:49 +0000 (UTC)
On 2012-05-14, Andy L <buggi22 at hotmail.com> wrote:
> I'm having trouble using sublist_indices on lists of symbols.
>?Basically, I'm trying to implement a function that will find the
> indices at which a given symbol appears within a list of symbols.
> Can anyone explain why the following code should yield [1] instead of []?
> ? f: lambda([l,x], sublist_indices(l, lambda([z], z = x)))$? f([x,y,z], a); ?/* this yields [1] */
Well, I was going to go on about lexical versus dynamic scope and
Maxima's evaluation policy, but I think the origin of this problem is
that there is a bug in a function named 'maybe', which is called by
sublist_indices to evaluate the predicate. 'maybe' explicitly evaluates
its argument (incidentally contravening Maxima's general one-time
evaluation policy) and that causes the confusion you observed.
Fixing 'maybe' isn't so easy because (short answer) logical predicates
are not simplifying functions.
A simple workaround in this case is, I think, to name the argument x% or
something else which is unlikely to cause a name collision. Yes, that is
a fragile solution.
> The same function behaves as expected when the arguments are strings:
> ? f(["x","y","z"], "a"); ?/* this yields [], as expected */
It works as expected with strings since a string can only evaluate to itself.
HTH
Robert Dodier