# Introduction to Wolfram Language

Introduction to Wolfram Language

## Programming with Built-in Computational Intelligence

Programming with Built-in Computational Intelligence

The Wolfram Language allows programmers to operate at a significantly higher level than ever before, by leveraging built-in computational intelligence that relies on a vast depth of algorithms and real-world knowledge carefully integrated over three decades. Scalable for programs from tiny to huge, with immediate deployment locally and in the cloud, the Wolfram Language builds on clear principles—and an elegant unified symbolic structure—to create what is emerging as the world’s most productive programming language and the first true computational communication language for humans and AIs.

## What you get from the Wolfram language

What you get from the Wolfram language

1. By far the largest web of algorithms ever assembled

2. World’s largest collection of computable knowledge

3. Includes three decades of state-of-the-art algorithm development in Mathematica, Mathematica is a stack of software use to do all kinds of technical computing.

4. Minimize size and complexity of code

5. Code readability; understandability; predictability; learnability; flexibility and interoperability across all domains

6. Incremental programming: any fragment of code is instantly runnable

7. Code can involve any kind of object, such as an image, document, etc.

8. Start using the Wolfram Language with no programming knowledge

9. Put natural language understanding into programs you write

10. Use symbolic expressions to standardize interactions with external data and programs

11. Seamlessly do incremental/exploratory programming

12. Instantly build visualizations and analysis around your code

13. Strong theoretical foundations

14. Long-term team led by Stephen Wolfram himself

2. World’s largest collection of computable knowledge

3. Includes three decades of state-of-the-art algorithm development in Mathematica, Mathematica is a stack of software use to do all kinds of technical computing.

4. Minimize size and complexity of code

5. Code readability; understandability; predictability; learnability; flexibility and interoperability across all domains

6. Incremental programming: any fragment of code is instantly runnable

7. Code can involve any kind of object, such as an image, document, etc.

8. Start using the Wolfram Language with no programming knowledge

9. Put natural language understanding into programs you write

10. Use symbolic expressions to standardize interactions with external data and programs

11. Seamlessly do incremental/exploratory programming

12. Instantly build visualizations and analysis around your code

13. Strong theoretical foundations

14. Long-term team led by Stephen Wolfram himself

## Scope of the Wolfram language

Scope of the Wolfram language

The documentation gives us access to the thousands of functionality available in the Wolfram Language or WL is we call it.

Writing your first program! Follow the instructions below

## Analysing a function

Analysing a function

There are about 5000 built-in functions to do many kinds of computation you want to do like Sorting numbers or anything. All built-in functions have a capital letter as the first letter and arguments are separated by commas.

Range[10]

In[]:=

{1,2,3,4,5,6,7,8,9,10}

Out[]=

NestList[function,arg,3]

In[]:=

{arg,function[arg],function[function[arg]],function[function[function[arg]]]}

Out[]=

The NestList function receives 3 arguments separated by commas, in this particular call the fist argument is supposed to be a function and the second argument the argument you want to apply the function to. the last argument 3 says how many times you want to do this nested function application.

## Building expressions

Building expressions

When we write programs in WL we are building expressions. Lets write a simple program that detects the edges of a sphere.

First we create a sphere this is a simple as typing the function call for a sphere which returns a symbolic expression of the sphere.

Sphere[]

Sphere[{0,0,0}]

Out[]=

Next we wrap the symbolic expression of the sphere inside another function that turns it into a visual sphere

Graphics3D[Sphere[]]

In[]:=

Out[]=

To detect edges we simply use the EdgeDetect function

EdgeDetect[Graphics3D[Sphere[]]]

In[]:=

Out[]=

You can see that with just using built-in functions we can do something that is algorithmically complicated like doing edge detection. I challenge you to find a programming language out there where you can do this in a single line! The power of WL

## Holding things with Lists

Holding things with Lists

When you’re performing computation, most of the time we hold our input data in Lists and return our output as Lists. Lists are the workhorse of WL and the most useful operation on them is indexing.

Lets create a list of fruits

Lets create a list of fruits

{oranges,bananas,mangoes,papaya,pineapple,pear}

In other programming languages I would have to store the fruit names as strings by putting double quotes “oranges”, but this is not necessary in WL. You can simple write oranges in a list and it stands for itself due to the symbolic nature of the language.

Lets select the 3rd item in this list, maybe we want to compute on it.

{oranges,bananas,mangoes,papaya,pineapple,pear}[[3]]

In[]:=

mangoes

Out[]=

Lets get the first

First[{oranges,bananas,mangoes,papaya,pineapple,pear}]

In[]:=

oranges

Out[]=

We can also use index number to get the first

{oranges,bananas,mangoes,papaya,pineapple,pear}[[1]]

In[]:=

oranges

Out[]=

Last[{oranges,bananas,mangoes,papaya,pineapple,pear}]

In[]:=

pear

Out[]=

Lets get all the items without the first

Rest[{oranges,bananas,mangoes,papaya,pineapple,pear}]

In[]:=

{bananas,mangoes,papaya,pineapple,pear}

Out[]=

Or all without the last

Most[{oranges,bananas,mangoes,papaya,pineapple,pear}]

In[]:=

{oranges,bananas,mangoes,papaya,pineapple}

Out[]=

Take the first 3

Take[{oranges,bananas,mangoes,papaya,pineapple,pear},3]

In[]:=

{oranges,bananas,mangoes}

Out[]=

## Iterating through things

Iterating through things

Although you have the basic For loop that you must have seen from other languages, and also the Do and the While, but our basic workhorse iterator is the Table

If you are tasked with computing the square of numbers from 1 to 10 this is how you would do it using Table

If you are tasked with computing the square of numbers from 1 to 10 this is how you would do it using Table

Table[num^2,{num,10}]

In[]:=

{1,4,9,16,25,36,49,64,81,100}

Out[]=

Lets do cubes

Table[num^3,{num,10}]

In[]:=

{1,8,27,64,125,216,343,512,729,1000}

Out[]=

Lets get cubes from 10 to 20

Table[num^3,{num,10,20}]

In[]:=

{1000,1331,1728,2197,2744,3375,4096,4913,5832,6859,8000}

Out[]=

Lets make the result also show the number beside the cube

Table[{num,num^3},{num,10,20}]

In[]:=

{{10,1000},{11,1331},{12,1728},{13,2197},{14,2744},{15,3375},{16,4096},{17,4913},{18,5832},{19,6859},{20,8000}}

Out[]=

We can get the cubes of only even numbers from 10 to 20

Table[{num,num^3},{num,10,20,2}]

In[]:=

{{10,1000},{12,1728},{14,2744},{16,4096},{18,5832},{20,8000}}

Out[]=

## Assignments

Assignments

Values can be assigned to variables using = or :=

age=120

In[]:=

120

Out[]=

Using = is called immediate assignment, meaning you want the value on the right hand side to be immediately given to the variable name. But if the value is something want recomputed anytime you call the variable then you use delayed assignment :=

t:=Now

In[]:=

t

In[]:=

Out[]=

After a short while we ask for the time again and we get a new value

t

In[]:=

Out[]=

## Patterns

Patterns

We use pattern expression to represent expressions in an abstract way without getting specific. it is used mostly to help us search and match things.

Cases[{f[1],g[2],f[5],g[3]},f[_]]

In[]:=

{f[1],f[5]}

Out[]=

The _ (pronounced “blank”) is used to match anything. In the example above the Cases function searches searches a list of expressions for anything matching the pattern f[ _ ] and it finds two expressions that match that criteria.

Rather than use a blank like that we can name it using a name like x_

Replace[f[10],f[x_]x+5]

In[]:=

15

Out[]=

The Replace function takes a function and performs a match and replace on the expressions.

/. means “replace everywhere”

{f[1],g[2],f[5],g[3]}/.f[x_]x+5

In[]:=

{6,g[2],10,g[3]}

Out[]=

__ (“double blank”) stands for any sequence of expressions:

Cases[{f[1,2],f[1],g[3]},f[__]]

In[]:=

{f[1,2],f[1]}

Out[]=

## Defining Functions

Defining Functions

So far we have been using built in functions that come with the Wolfram language. All we need to do is just supply the needed arguments. But we can also come up with our own functions to do the things we want to do and doing so is very easy!

First lets create a number that squares it’s input! Remember how we used Iterators to square a list of numbers, this time around we will use a function. A function is like a machine that takes input, performs operations on that input and returns some output

First lets create a number that squares it’s input! Remember how we used Iterators to square a list of numbers, this time around we will use a function. A function is like a machine that takes input, performs operations on that input and returns some output

square[x_]:=x^2

In[]:=

square[46]

In[]:=

2116

Out[]=

When defining our own functions it is customary to start the names with lower case letters so that we don’t conflict with the built in names.

add[x_,y_]:=x+y

In[]:=

add[43,6]

In[]:=

49

Out[]=

Multi-argument functions are also easy, just separate the arguments with a comma. You define much more complex functions by building expressions we will see that in the computational thinking section.

## Pure functions

Pure functions

There are also what we call pure functions or anonymous functions. These functions can be defined inline and do not need a name. We can redefine the functions above as pure functions and name them later. The square function will then be

#^2&

In[]:=

2

#1

Out[]=

The # represents the argument while the & terminates the function expression. We can supply arguments to the pure function too.

#^2&[46]

In[]:=

2116

Out[]=

We can name it to reuse it, but if you require named functions its better off to just do a full function definition. But lets name it.

sq=#^2&

In[]:=

2

#1

Out[]=

sq[42]

In[]:=

1764

Out[]=

We can do multiple arguments

#1-#2&

In[]:=

#1-#2&

Out[]=

Supply arguments

#1-#2&[43,2]

In[]:=

41

Out[]=

Another way to specify the subtraction function above is

Function[{x,y},x-y][43,2]

In[]:=

41

Out[]=

We use the function Function (lol) to define anonymous functions. We pass arguments to the function in the first argument of Function and then the second argument of Function is the body of the function. Then we can use our calling convention [ ] to call the function and supply values for the arguments. Re-read this section paying attention to capitalization of Function and function.

We use anonymous function in places where a function definition is needed for some one off operation and we don’t want to do a fully definition like in the Select function.

Select[{3,5,23,4,6,2,10,12},#>7&]

In[]:=

{23,10,12}

Out[]=

The anonymous function supplied as the last argument of the Select function is used of filter the list, picking out only number that a strictly greater than 7.

## Mapping and Applying functions

Mapping and Applying functions

A common operation in WL programming is mapping and applying functions over expressions.

Below we Map the function Capitalize over a list of animals. It capitalizes the first letter of the string.

Below we Map the function Capitalize over a list of animals. It capitalizes the first letter of the string.

Map[Capitalize,{"cats","dogs","mice","zebra"}]

In[]:=

{Cats,Dogs,Mice,Zebra}

Out[]=

Map applies a function over an expression! Lets look at an abstract example to see what is going on

Map[f,{a,b,c,d}]

In[]:=

{f[a],f[b],f[c],f[d]}

Out[]=

We can see much clearly what Map is doing! it is picking out each element of the list expression and applying f over it. f here represents some function.

We can use the /@ short form notation for Map.

We can use the /@ short form notation for Map.

f/@{a,b,c,d}

In[]:=

{f[a],f[b],f[c],f[d]}

Out[]=

We can use pure functions

{#,#}&/@{a,b,c,d}

In[]:=

{{a,a},{b,b},{c,c},{d,d}}

Out[]=

Apply on the other hand applies a function to multiple arguments

Apply[f,{a,b,c,d}]

In[]:=

f[a,b,c,d]

Out[]=

Expressions have “levels” -- corresponding to the number of indices needed to extract a part. Functions like Map can operate at specific levels.

Map defaults to operate at level 1

Map defaults to operate at level 1

Map[f,{{a,b},{c,d}}]

In[]:=

{f[{a,b}],f[{c,d}]}

Out[]=

Lets Map at level 2

Map[f,{{a,b},{c,d}},{2}]

In[]:=

{{f[a],f[b]},{f[c],f[d]}}

Out[]=

@@ is equivalent to Apply, operating by default at level 0

f@@{{a,b},{c,d}}

In[]:=

f[{a,b},{c,d}]

Out[]=

@@@ means “apply at level 1”:

f@@@{{a,b},{c,d}}

In[]:=

{f[a,b],f[c,d]}

Out[]=

@ simple means ordinary function application

sq@2

In[]:=

4

Out[]=

sq[2]

In[]:=

4

Out[]=

## Operator form of functions

Operator form of functions

Many built-in functions in the Wolfram language can use the operator form, where the function is applied as an operator to arguments.

randomNumbers=RandomInteger[20,10]

In[]:=

{1,10,2,14,6,12,5,1,3,17}

Out[]=

Lets find the number in this list above that is nearest to 7.5

Nearest[randomNumbers,7.5]

In[]:=

{6}

Out[]=

We can setup the operator form of the nearest function and apply it to arguments.

Nearest[randomNumbers]

In[]:=

NearestFunction

Out[]=

Now we apply it to arguments

nf=%(*The%operatorrecalsthepreviousoutput*)

In[]:=

NearestFunction

Out[]=

nf[7.5]

In[]:=

{6}

Out[]=

Lets try another number

nf[3.2]

In[]:=

{3}

Out[]=

Remember the Select function with this pure function # > 7& ? lets build a Select operator.

Select[#>7&][randomNumbers]

In[]:=

{10,14,12,17}

Out[]=

## Supplying options to functions

Supplying options to functions

Many built-in functions have “options” that affect the details of thier operation or output.

Framed[Wolfram]

In[]:=

Out[]=

With an option we can change the background color of the frame

Framed[Wolfram,BackgroundLightBlue]

In[]:=

Out[]=

To investigate the available options of a function simply

Options[Framed]

In[]:=

{AlignmentAutomatic,BackgroundNone,BaselinePositionAutomatic,BaseStyle{},ContentPaddingTrue,DefaultBaseStyle{},DefaultFrameStyle{},FrameMarginsAutomatic,FrameStyleAutomatic,ImageMargins0,ImageSizeAutomatic,RoundingRadius0,StripOnInputFalse}

Out[]=

Some options are given as pure functions

Plot3D[Sin[xy],{x,0,3},{y,0,3},ColorFunction(Hue[#3/3,.5]&)]

In[]:=

Out[]=

## Easy visualization

Easy visualization

One of the biggest advantage of using the Wolfram system is in it’s powerful visualization system. You don’t need to “import” any libraries! All visualization capacities are built-in directly into the language making it very efficient.

ListLinePlot[randomNumbers]

In[]:=

Out[]=

Remember randomNumbers is a list of randomly generated numbers we got earlier.

Creating and visualizing graphs is also super easy.

Graph[{15,13,17,37,78,85}]

In[]:=

Out[]=

## Manipulating stuff

Manipulating stuff

We can take any expression and build interactive interfaces with them without doing any kind of GUI programming.

Manipulate[Plot[Sin[ax],{x,0,10}],{a,1,5}]

In[]:=

Out[]=

Simply moving the slider about and we can change the value of the variables a and x and thus see changes instantly in the graph below.

## Procedures, Control flow and conditionals

Procedures, Control flow and conditionals

The programming structures you have in other languages are all available in Wolfram but in many cases you do not need them and can just use functions for many tasks. But if you need them they are there. If you have a big program full of If, Do, Return, etc. you’re probably not doing things right.)

Module is used to localize variables

Module[{a=1},a+8]

In[]:=

9

Out[]=

With is used to set constants, the difference in effect of With is very subtle. In this short introduction to the language I will not go into it but when you read programs you will see the subtlety in the computational thinking section.

With[{b=2},b*4]

In[]:=

8

Out[]=

Do[Print[i];Print[i*2],{i,3}]

In[]:=

1

2

2

4

3

6

The semi-colon is used to separate different operations

i=1;While[i<5,Print[i];i++]

In[]:=

1

2

3

4

While is a simple function that requires 2 arguments, the test and the body.

If[6>5&&2≤5,a,b]

In[]:=

a

Out[]=

If is a function that requires 3 arguments, the test, what to do if test is true, what to do if test is false.

## Using Wolfram language as a calculator

Using Wolfram language as a calculator

3/8+7/23

In[]:=

125

184

Out[]=

Most of the time computations are exact but you can get numerical results

N[3/8+7/23]

In[]:=

0.679348

Out[]=

You can handle numbers of any precision in WL. lets get Pi to 50 decimal digits

N[Pi,50]

In[]:=

3.1415926535897932384626433832795028841971693993751

Out[]=

Lets get 200 digits

N[Pi,200]

In[]:=

3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303820

Out[]=

You’re only limited by the size of the memory on your computer.

## Associations aka dictionaries

Associations aka dictionaries

If you come from a Python background you must have seen the way Key, Value pairs are stored as dictionaries. In WL we call them Associations.

<|"name""John Carter","Planet""Mars","Phone"5551658|>

In[]:=

nameJohn Carter,PlanetMars,Phone5551658

Out[]=

"name""John Carter","Planet""Mars","Phone"5551658["name"]

In[]:=

John Carter

Out[]=

We extract values by indexing with the appropriate key.

{#Phone,2*#Phone}&["name""John Carter","Planet""Mars","Phone"5551658]

In[]:=

{5551658,11103316}

Out[]=

Using a pure function and #key to extract a value.

## Natural language input

Natural language input

Sometimes you don’t need to type code to do stuff. Wolfram language accepts natural language input.

In[]:=

Out[]=

## Real World entities

Real World entities

We can compute with real world entities like any other symbolic expression. We can compute with countries, cities, chemicals, species,people, movies,satellites, airports, etc. Image the power of such a system.

You can enter units and measures directly using CTRL + =

## Cloud Deployment

Cloud Deployment

Instantly deploy web apps unto the Wolfram Cloud. You can create sophisticated web apps with as little code as possible. Let us create a simple web app that returns a map around a particular geographic area!

CloudDeploy[FormFunction[{"place""Location","radius""Quantity"},GeoGraphics[GeoDisk[#place,#radius]]&,"PNG"]]

In[]:=

CloudObject

Out[]=

What you have to do next is click the link above and it will open your newly created web app in a browser

As simple as ABC we just created a Web app that would have been ridiculously complicated to do on any other platform. You are not limited to maps, any computation you can conceive of can be deployed on the Cloud and with appropriate permissions, you can invite others to use your app!

## External Connections

External Connections

The Import and Export functions automatically handle hundreds of formats from files, programs, the web, etc.:

Import["https://www.nps.gov","Images"]

In[]:=

,,,,,,,,,,

Out[]=

You can even compute directly on social media data like connecting to a Facebook account

## What next?

What next?

We have done a very light tour of the capabilities of the Wolfram language. Programming like any endeavour is a lifelong process of mastery. The Wolfram language is BIG with about 5000+ functions for do all kinds of things. We cannot cover all of the language in a session as brief as this but I have given you a taste of whats available and as much of the language as we will need to do AI/ML

In the next module on Computational Thinking we will see how you can apply the concepts you have learnt here to think computationally.

Stephen Wolfram’s Introductory book: An Elementary Introduction to the Wolfram Language available online for free to read goes into greater details of the Wolfram language than I have done in this Quick Introduction. The purpose of the Introduction is to prepare you to use the language features that we need for AI/ML.

For those who need a more hands-on approach to learning the language the Wolfram Programming Lab is available

The entire language is neatly documented in the Documentation Center

These are the resources you need to start developing your Software Engineering Career.

## What is computational thinking?

What is computational thinking?

If we want to solve problems in a sophisticated way, we cannot use Natural Language to express our ideas. The first step in humanity’s technical history was with Mathematical thinking which built the society we live and all enjoy. But there is a new kind of thinking on the horizon, it is called computational thinking.

Computational thinking is kind of like a superset of mathematical thinking, because the equations that are the foundation of mathematical thinking can be expressed with a powerful symbolic language like the Wolfram language. Apart from being naturally able to do mathematical thinking in a computational language, we can also do things that are not purely mathematical but more generic computational things.

Computational thinking is kind of like a superset of mathematical thinking, because the equations that are the foundation of mathematical thinking can be expressed with a powerful symbolic language like the Wolfram language. Apart from being naturally able to do mathematical thinking in a computational language, we can also do things that are not purely mathematical but more generic computational things.

Whenever you are trying to solve a computational problem, or a problem that arises in your own activities like finding the shortest tour around Europe or any other country for that matter, you are doing computational thinking.

## The need for interactivity

The need for interactivity

You don’t need to write a full blow software application to do computational thinking, you need an interactive notebook like the Wolfram Notebook.

An interactive environment requires that we can get instant output from the programmatic expressions that we make without waiting for any full compilation process that is required in traditional software engineering.

An interactive environment requires that we can get instant output from the programmatic expressions that we make without waiting for any full compilation process that is required in traditional software engineering.

We write code, run it, and instantly get results in the output cells of our Wolfram notebook. This is real computational thinking because we are trying to solve a computational problem instantly, most of the time using only the built in functionality of the language.

Without much ado, we will go into the details of computational thinking by building expressions that solve real world problems in this module. I want to give you the best. Although in Wolfram language we can perform large computations with only a single function like this:

ImageRestyle,

In[]:=

Out[]=

But in this module we are going to focus on long form examples of Computational thinking to solve real world problems. You can find a lot of these short form examples of Computational thinking in Stephen Wolfram’s book or about 100,000+ of them in the documentation.

## Handwritten digit classification

Handwritten digit classification

This is the classical “hello world” example of the machine learning world. The goal of the program is to enable us determine which digit is represented in a typical handwritten digit. While this is a breeze for humans to perform, it is advanced stuff for computers.

First we need the training data

data=1,2,1,2,4,8,9,9,3,7,1,5,5,2,7,3,8,9,8,2,0,9,7,1,5,3,7,8,9,4,7,2,7,1,7,5,9,8,8,5,0,1,5,2,9,2,9,5,9,2,1,2,3,5,9,3,1,3,3,1,9,3,3,9,2,9,9,1,8,8,0,7,7,7,0,6,2,3,8,3,1,2,6,4,1,6,3,7,3,0,1,9,0,7,1,9,9,2,7,2;

In[]:=

The training data is a mapping (a -> b) of handwritten digits to standard computer digit characters. Next we use the automatic classifier built into the Wolfram language to do the classification. This would be a laborious process in any other language.

digit=Classify[data]

In[]:=

ClassifierFunction

Out[]=

Next we test the classifier function on images that were not in the train set.

digit,,,,,,,

In[]:=

{1,0,8,3,5,1,5,1}

Out[]=

As we can see from the results in the output line, there were errors with the classification because the data we used was insufficient. It is always a good thing to get a lot of data to improve the accuracy.

Let us get the complete MNIST data from the Wolfram Data Repository

trainingData=ResourceData["MNIST","TrainingData"];

In[]:=

Lets take a random sample of 10 training examples from the trainingData

RandomSample[trainingData,10]

In[]:=

4,7,3,6,5,9,6,0,5,6

Out[]=

We can see that it looks like what we had before but lets see how many training examples are in trainingData

Length[trainingData]

In[]:=

60000

Out[]=

We have 60,000 examples! that’s good enough to enable the system learn properly compared to what we had before. Now let’s use the automatic classification system to classify the data and get a classifier function.

digitFulldata=Classify[trainingData]

In[]:=

ClassifierFunction

Out[]=

This is the GUI that pops up while doing automatic classification but it disappears after classification is finished. Lets use our new classifier function to classify the previous example that failed.

digitFulldata,,,,,,,

In[]:=

{2,0,8,3,9,6,5,1}

Out[]=

We get 100% accuracy now. This is our first example of computational thinking. We were giving the task of classifying handwritten digits and we used the Classify built-in function to classify the training data. The next step was to use the classifier function that was output from the Classify function to classify some test data and we got 100% accuracy.

## Classify Images as Day or Night

Classify Images as Day or Night

Lets take our classification of things a step further. We are going to make a function that recognizes whether an image was taken during the day or during the night. Classification is a core task in machine learning and artificial intelligence so it makes sense to see another variation.

daynightData="Night","Day","Night","Night","Day","Night","Day","Day","Night","Night","Day","Night","Night","Day","Night","Night",