Puzzles/If Then Else or Case

From J Wiki
Jump to navigation Jump to search

A user posed the question: Given a list of integers, set each item that is less than n1 to n2 . Can it be expressed without an explicit loop?

Addition and Multiplication by Boolean Masks

(x * b) + (y * -.b)

x and y are conformable numeric arrays, and b is a conformable boolean array. An element of the result corresponding to where b is 1,  is taken from x,  where b is 0 , is taken from y .

Using this to answer the original question:

(list * n1 <: list) + n2 * n1 > list

Item Amend

b}x,:y

See http://www.jsoftware.com/books/help/release/iamend.htm . The phrase works on non-numeric arrays, and can be generalized to select from more than two cases, c}x,y,...,:z .

Using this to answer the original question:

(n1 > list)} list,:n2

Direct Amend

Amend can also be use dyadically. This phrase also works on non-numeric arrays. Here, x must be conformable as an item or +/b items of y.

x (I. b)} y

Using this to answer the original question:

n2 (I. n1 > list)} list

Implicit programing

This is a short generalization, since instead of replacing each item less than n1 with n2, you can replace them with an arbitrary value depending on the item.

n2"0^:(n1&>)"0 list