9

Here is a toy example to illustrate my problem. I have a list of 3-tuples and I want to delete elements from this list that satisfy a condition shown below.

tuples = Tuples[{-1, -2, 3}, {3}];
DeleteCases[tuples, _?((#[[1]] + 2 #[[2]] + #[[3]] == 0) &)]

This works perfectly. However, because each element of tuples has this form {a,b,c} and symbols a, b, c have problem-specific meanings attached to them, the code would become more readable if written as follows:

tuples = Tuples[{-1, -2, 3}, {3}];
DeleteCases[tuples, _?((a + 2*b + c == 0) &)]

The motivation is that a + 2*b + c == 0 is easier for a human to read and understand than (#[[1]] + 2 #[[2]] + #[[3]] == 0.

Question Is it possible to write this code using variables instead of slots?

Syed
  • 52,495
  • 4
  • 30
  • 85
hana
  • 2,388
  • 5
  • 19

4 Answers4

12
tuples = {{1, 1, -3}, {1, 2, 3}};

(* Solution 1: *)
DeleteCases[tuples, {a_, b_, c_} /; a + 2 b + c == 0]
(* {{1, 2, 3}} *)

(* Solution 2: *)
DeleteCases[tuples, _?(({a, b, c} |-> a + 2 b + c == 0) @@ ## &)]
(* {{1, 2, 3}} *)

(* Solution 3: *)
test[{a_, b_, c_}] := a + 2 b + c == 0  
DeleteCases[tuples, _?test]
(* {{1, 2, 3}} *)
xzczd
  • 65,995
  • 9
  • 163
  • 468
12

Pick could also be useful:

Pick[tuples, Function[{a, b, c}, a + 2 b + c == 0] @@@ tuples, False]
Ben Izd
  • 9,229
  • 1
  • 14
  • 45
8

Perhaps (Thanks to comment/correction @BenIzd )

DeleteCases[tuples, _?(Apply@Function[{a, b, c}, a + 2 b + c == 0])]

is what you are looking for?

Ulrich Neumann
  • 53,729
  • 2
  • 23
  • 55
8
g[{a_, b_, c_}] := a + 2 b + c == 0

Using the operator form:

DeleteCases[x_ /; g[x]][tuples]
Syed
  • 52,495
  • 4
  • 30
  • 85