Reputation: 13
I have some questions, can anybody show how to solve them?
1)How to count elements of list specific to level, independently of sort Exrp? Just like the number of elements subset. for example {{1,2,3,4,5},{5,6,7,8,9}} , at level 1 it should yield 10. I ve been trying to done this by Count[] , but it dont work so even if i choose pattern _ (i can count them separately specifying pattern, but i cant use multi-pattern (see below) , if i specifying _ then it count some lists above target level).
2)How i can assert something like NumberQ or EvenQ to content of list using list as function argument (ie list must contain specific mathematica expr. ) and how to create multi pattern like( f[x_List?NumberQ or EvenQ,y_List?NumberQ or EvenQ]
Thanks.
Upvotes: 1
Views: 379
Reputation: 745
The first question has already been answered in comments.
For the second version, -Q functions are not automatically threaded and combined (as there are several ways to combine tests on a list). You have to do explicitely.
Here is one way to do it:
f[x_List,y_List]:= Join[x,y] /; (And@@Map[EvenQ,x] && And@@Map[EvenQ,y])
This syntax defines how to compute f
if the conditions on the right are satisfied. f
will remain unevaluated if at least one test does not yields true.
If the kind of test you like comes often, you can define auxiliary functions:
test if a list contains only even numbers
evenlistQ[x_List]:= And@@Map[EvenQ, x]
test if a list contains only items verifying both test_A and test_B
AandBlistQ[x_List]:= And@@Map[testA[#]&&testB[#]&, x]
test if a list contains only items verifying at least one of test_A or test_B
AorBlistQ[x_List]:= And@@Map[testA[#]||testB[#]&, x]
test if a list is either completely verifying test_A or completely verifying test_B
AlistOrBlistQ[x_List]:= (And@@Map[testA,x] || And@@Map[testB,x])
Then you could write
f[ x_List?evenlistQ, y_List?evenlistQ] := Join[x,y]
that would evaluate only if both arguments are lists of verifying your requirements and left unevaluated if not.
This last form is equivalent to
f[ x_List, y_List] := Join[x,y] /; (evenlistQ[x]&& evenlistQ[y])
which allows more flexibility for constraints verification.
Upvotes: 1