On several occasions, while working with lists or Matrices, I have been drawn to using a combination of seq and if, as in the following:
seq(`if`(a,b,c), i = 1 .. 10 )
This appears to be a powerful approach. Unfortunately, I have not found much documentation on it.
I have been able to pattern-guess to a limited extent for my limited needs.
Would you know of a good place to go for information?
My understanding is: "a" is the conditional statement, "b" is the action if the statement is true, and "c" the action if the statement is false. Is that roughly correct?
Let me gather some examples I have found useful. Feel free to comment, add your own examples, point out limitations, etc..
# Create a random list and a random Matrix
n := 50:
L := RandomTools:-Generate(list(integer(range=-100..100),n)):
M := Matrix(n,n,RandomTools:-Generate(integer(range=-100..100),makeproc=true)):
# Example 1
# Count how many elements of a list are within a given interval
# In this example I use add instead of seq, using a similar syntax
add(`if`(L[i] < 0, 1, 0) , i = 1 .. n );
# Example 2
# Stephen Forrest, also comments on efficiency and alternatives
# Make a list of prime numbers
[seq(`if`(isprime(i),i,NULL), i = 1 .. n )];
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
# Find the prime numbers in a list (returns position)
[seq(`if`(isprime(L[i]),i,NULL), i = 1 .. n )];
[14, 16, 24, 29, 30, 31, 35, 37, 50]
# Example 3
# pagan, gives a more general example
# return all indices of a list such that two consecutive elements are any pair of consecutive integers
L := [op(L),1,2,3]: # making sure such occurrences exist
# Example 4
# In a Matrix delete all rows that have negative entries in the first column
I think that these and other examples like these and more should be added to the documentation.