I am attempting to implement the exercises from The Little Schemer in Mathematica, and running to a bit of a challenge with rember (remove member). Given a list and a value, the function just returns the list with occurrences of value removed.
rember[a_, lat_] :=
Return[
If[NullQ[lat],
Return[lat]
,
If[a == First[lat],
Return[rember[a, Rest[lat]]],
Return[Cons[First[lat], rember[a, Rest[lat]]]]
]
]
]
I created the helper functions NullQ and Cons based on The Little Schemer as well, with NullQ being true/false if a list is Null, and Cons being a wrapper around Prepend:
Cons[a_, lst_] :=
If[x === Null, Return[{a}], Return[Prepend[lst, a]]]
NullQ[x_] := If[ListQ[x],
If[Length[x] == 0,
Return[True],
Return[False]]
, Return[False]
];
The idea in rember is if it's Null, the recursion ends, otherwise it checks the first item of the list, if that's a match it calls remember with the remainder of the list, if it's not a match it prepends that value onto calling rember with the remainder of the list.
I think my logic is correct, but returns are not working correctly. How do I construct this list recursively? I'm sure my code is bad on several levels, thank you in advance for any advice you have.
EDIT: corrected code to not return a serially.