:

## The mysterious `if`

Maple

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..

restart;
# 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 );

27

# Example 2
# http://www.mapleprimes.com/posts/43630-Finding-The-Set-Of-Prime-Numbers--N
# 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
# http://www.mapleprimes.com/questions/135686-Searching-A-List-For-Two-Consecutive-Elements
# 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

[seq(`if`(L[i+1]=L[i]+1,i,NULL),i=1..nops(L)-1)];

[51, 52]

# Example 4
# http://www.mapleprimes.com/posts/127832-Deleting-Rows-In-A-Matrix
# In a Matrix delete all rows that have negative entries in the first column

Matrix(<seq(`if`(M[i,1]>0,M[i,1..-1],NULL),i=1..op([1,1],M))>):
%[1..10,1..10];

I think that these and other examples like these and more should be added to the documentation.

﻿