## Functions

Managing inputs and outputs is a key problem programming languages face. Here's how a few languages use functions to manage and transform data.

This Code Snippets section of the magazine explains parts of programming languages common across most or all languages. It's a great way to understand how languages work. And it helps reduce the ability of a new programming language to glaze your eyes. Learning how to code should be much easier and less frightening if I explain a part of a programming language, then show you how it works in a couple different languages.

Let's get started by talking about functions.

### What’s a Function?

Every programming language lets you create blocks of code that, when called, perform tasks. Imagine a dog that does the same trick only when asked. Except you do not need dog treats to make your code perform. In programming, these code blocks are called functions.

All programming functions have input and output. The function contains instructions used to create the output from its input. It’s like a cow that eats grass (the input) which its body turns into milk which a dairy farmer then milks (the output).

For example, programming functions might take as input any integer or number. The function might create output by multiplying the input times two. Therefore, the output of the function would be double its input.

Or imagine the short Hello message you sometimes see in online software applications at the top right corner of any page. The function would take as input your name (or user number) from the application and drop your name (or look up your name with your user number) into the phrase “Hello [your name]!” If your name is Jane, the output of this function would be “Hello Jane!”

It is possible to build entire software applications with only functions. Programming languages which primarily use functions are called functional programming languages. Haskell and a few other languages are primarily functional languages. You build software by building blocks of code that perform specific tasks.

### Functions and Scope

One issue with any programming, whether with blocks of functions or other approaches, is how to manage scope. If you have a function that returns a value, say 42, is 42 available to use only in your function? Or is 42 available for use elsewhere in your code? And, if 42 is available elsewhere, can you make it available all the time, like God, or only in a limited way?

Here's what I mean in plain English. Let's create a function that, when called, prints out “Hello World!” We'll name this function hello_world(). Clearly I can call hello_world() anywhere in my code and it will print out (display) the phrase, “Hello World!”

I also can have the hello_world() function return the same phrase. The output will not display unless you call hello_world() then have your call print or display the result. For example, I can create a variable, \$hello, set it equal to the output of my hello_world() function, then echo (or display, or print on the computer screen) the output of my function: “Hello world!”

Therefore, the phrase “Hello world!” exists in two possible forms:

• I create the hello_world() function to simply print out the phrase.
• I create the hello_world() function to return the phrase, not print it out.

In many languages, there's also a third way to make the phrase exist, available everywhere in your application. I could write my function hello_world() to set a session value or global value of the phrase, “Hello World!” Then I could set the variable \$hello to be the global value set by my hello_world() function. Because my programming language makes global values available everywhere, my \$hello variable value would be available everywhere.

There are limitations, of course. There might be security issues with making data available globally. If your function uses a database to create output, for example, to retrieve a user’s name, it might be more efficient to return the output so you can create a variable once to store the output then use the variable to display the output in many places in your code.

This is a very rough description of programming functions and scope but it should set you up to learn more about any language that uses functions.

### Functions and Testing Software

Talking about functions is a great time to talk about how to test software. Testing is a big deal in software development. Functions are the smallest, and most natural, unit to test as you code software. These tests are called unit tests. Unlike other software testing, the purpose of a unit test is only to confirm the function (or small blocks of code) do what they are designed to do.

In our hello_world() example, our unit test would be very simple: confirm the function outputs the phrase “Hello World!” in the way we designed the function. As noted, we could design our hello_world() function to display the phrase by:

• Calling the function and the function would display the phrase.
• Returning a value that could be assigned to a variable like \$hello.
• Creating a global value we could assign to a variable like \$hello.

Whatever method we choose, our unit test would confirm our function performed as we intended.

### Example of Programming Functions in Different Languages

Next, let's look at how a few languages implement programming functions, both the function structure and how to call a function in different languages.

#### PHP

First, a PHP function to simply double any input value then quickly print display the results:

```function do_double(\$input) {
\$output = \$input * 2; //double the input value
echo \$output; //print display \$output result
}
echo do_double(2);
```

Notice a few things with this code:

• PHP uses the function keyword to tell the language a function is about to be defined.
• Functions in PHP are names with underscores (_) instead of empty spaces followed by parentheses ( ) to hold any input values.
• The contents of a function in PHP are marked off by curly braces { }. The start of the function begins with the left curly brace { and ends with the right curly brace {. Every left brace must be matched with a right brace or PHP will throw an error.
• echo is a PHP command that immediately prints whatever value(s) appear to its right, in this case the \$output variable.
• echo do_double(2) calls and print outputs the do_double() function passing the function the input of 2. The result should be 2 * 2 or 4.
• Imagine if \$input was text like “cat”: echo \$output would fail, wouldn’t it? In this example, our function also needs to test \$input is a number. Testing input values is a key part of creating functions.

Second, a PHP function to simply double any input value then return the results:

```function do_double(\$input) {
\$output = \$input * 2; //double the input value
return \$output; //return \$output result to whatever calls this function
}

\$double = do_double(2);
echo \$double;
```

Notice a few things with this code:

• This time we use return instead of echo inside the do_double() function. The \$output value will not appear automatically when we call this function.
• The \$double variable is assigned (=) the value results of the do_double() function with an input of 2. The \$output value should be 2 * 2 or 4.
• The last step is to echo display the value of the \$double variable.

#### Go

The Go programming language uses functions in an interesting modular way. Here is a basic “Hello World!” function:

```package main

import "fmt"

func main() {
fmt.Println("Hello, world!")
}
```

Notice these details:

• package main tells Go to load into memory a package called main that includes basic functionality used in Go applications. A package is a set of code to be used in more than one place in an application or more than one program.
• import “fmt” loads into memory a Go package to format output.
• The fmt.Println() command uses the fmt package to print display the content contained in the braces ( ).
• In Go, the func keyword tells the language a function is about to be defined. main() is a catch-all function in the Go language to do one or more things when the application is run.
• As with PHP and other programming languages, the contents of a function are marked off by curly braces { }. The start of the function begins with the left curly brace { and ends with the right curly brace {. Every left brace must be matched with a right brace or Go will throw an error.

And here is a slightly more complicated function in Go:

```package main

import "fmt"

func plus(a int, b int) int {
return a + b
}

func main() {
res := plus(1, 2)
fmt.Println("1+2 =", res)
}
run functions.go
1+2 = 3 //output of fmt.Println in main()
```

Notice these details:

• package main tells Go to load into memory a package called main that includes basic functionality used in Go applications. A package is a set of code to be used in more than one place in an application or more than one program.
• import “fmt” loads into memory a Go package to format output.
• The fmt.Println() command uses the fmt package to print display the content contained in the braces ( ).
• In Go, the func keyword tells the language a function is about to be defined.
• As with PHP and similar languages, the contents of a function are marked off by curly braces { }. The start of the function begins with the left curly brace { and ends with the right curly brace {. Every left brace must be matched with a right brace or Go will throw an error.
• The function plus() has two inputs, a and b. Each input is an integer as indicated by the int keyword immediately to the right of each input. The int keyword to the right of the func call indicates the output of the function is an integer.
• return a + b adds the value of a + b but does not display the result unless the plus() function is called.
• The main() function calls the plus() function as a result with res := which sets the result to whatever the plus() function returns when you give it inputs of 1 and 2. If you look up at the plus() function, you see inputs of 1 and 2 will result in 1 + 2, or 3.
• The main() function then uses the fmt package to print the results of what is inside the Println() command. In this case, the phrase “1+2 =” followed by the output of the res := result assignment on the line above.
• run functions.go executes the main() function which, in turn, executes the plus() function. The output is “1+2 = 3”.
• In Go, the double forward slash ( // ) indicates the start of a comment which Go ignores but helps humans understand the purpose of the code.

#### Lua

Lua has a two ways to define functions, as a single line of code assigned to a variable:

```double = function (n) return n*2 end

-- print display value of double with input of 7
= double(7)
```

or the more traditional multiple lines of code neatly ordered and indented:

```function double (n)
return n*2
end

-- print display value of double with input of 7
= double(7)
```

Both of these functions are written correctly. The Lua language prefers the single line definition to make it clear to coders functions are values like integers and strings of text. In this case, the variable name double in the first example and function name double both represent a value in Lua. The first example, with the variable double assigned to the function to its right is considered more accurate because it makes clear the function is a value.

For both Lua function notations, notice these details:

• The single line function “function (n) return n*2 end” is profoundly simple and, once you grasp Lua syntax, easy to read. The syntax is variable, equal sign, function keyword (function), input in parentheses, body of the function, and end keyword to indicate where function terminates.
• In both examples, an equal sign ( = ) by itself on the left tells Lua to print display what follows on the right side of the equal sign.
• In Lua, the double dash ( — ) indicates the start of a comment which Lua ignores but helps humans understand the purpose of the code.

#### PHP Functions

http://us1.php.net/manual/en/language.functions.php

#### Return Statements (Wikipedia)

https://en.wikipedia.org/wiki/Return_statement

## Author

• Tim is an award-winning writer and technologist who enjoys teaching tech to non-technical people. He has many years experience with web sites and applications in business, technical, and creative roles. He and his wife have two kids, now teenagers, who are mad about video games.

### My Adventures with Raspberry Pi

Open source hardware geared towards artists, hobbyists, designers, and students, is a viable and far less expensive alternative to build your own computers.

### Beth Rosenberg Talks How Tech Kids Unlimited Helps Kids Who Learn Differently

With a wave of kids with special needs graduating high school, how can technology help them with resumes, college, jobs, and careers?

### Stop Words

A clever technique to speed up database searches also is an interesting concept.

### More Fun with Raspberry Pi

Here are some videos, and links to even more videos, to learn how to use your Raspberry Pi and have all kinds of fun with Pi projects.

### News Wire Stories for November 2013

Interesting stories about computer science, software programming, and technology for the month of October 2013. More stories can be found at the Software Programming and Computer Science News Wire link at the top of every page of this site.

### Bubble Sorts

With a bubble sort, numbers sort themselves as they bubble to the left of a group of numbers. Here's a fun catchy video to explain.

### The 7 Bridges of Königsberg

This month's math puzzle dates back to 1735 when it was first solved by Leonhard Euler, a Swiss mathematician and physicist.

### Pair Programming

From the start of computing history, people have tried to optimize the software programming process. This includes having two coders work together to code software.

Links from the bottom of all the November 2013 articles, collected in one place for you to print, share, or bookmark.

A balance of flexible and inflexible qualities make Haskell a fascinating programming language to learn and use.

### Icon-itis

The release this fall of Apple's iOS7 operating system is a great opportunity to explore the history of computer interface design.

### Functions

Managing inputs and outputs is a key problem programming languages face. Here's how a few languages use functions to manage and transform data.

Interested but not ready to subscribe? Sign-up for our free monthly email newsletter with curated site content and a new issue email announcement that we send every two months.

No, thanks!