Introduction to Programming with Mathematica, Third Edition

4.7: One-liners

4.7 One-liners

In the simplest version of a user-defined function, there are no value declarations or auxiliary function definitions; the right-hand side is a single nested function call whose arguments are the names of the arguments on the left-hand side, without the blanks. These "one-liners" are fantastically useful and so we will discuss them in the context of three examples, one from electrical engineering (computing Hamming distance), one from ancient history (the Josephus problem), and the last a simple and practical problem (counting change).

Hamming distance

When a code is transmitted over a channel in the presence of noise, errors will often occur. The task of channel coding is to represent the source information in a manner that minimizes the error probability in decoding. Hamming distance is used in source coding to represent an information source with the minimum number of symbols. For two lists of binary symbols, the Hamming distance is defined as the number of nonmatching elements and so gives a measure of the how well these two lists match up.

Let us first think about how we might determine if two binary symbols are identical. SameQ [ x, y] will return True if x and y are identical.

    <i class="emphasis">In[1]</i>:= <b class="bold">{SameQ[0, 0], SameQ[1, 0], SameQ[1, 1]}</b>    <i class="emphasis">Out[1]</i>= {True, False, True}

So we need to thread SameQ over the two lists of binary numbers

    <i class="emphasis">In[2]</i>:= <b class="bold">MapThread[SameQ,...

UNLIMITED FREE
ACCESS
TO THE WORLD'S BEST IDEAS

SUBMIT
Already a GlobalSpec user? Log in.

This is embarrasing...

An error occurred while processing the form. Please try again in a few minutes.

Customize Your GlobalSpec Experience

Category: Waveplates and Retardation Plates
Finish!
Privacy Policy

This is embarrasing...

An error occurred while processing the form. Please try again in a few minutes.