« Find the size of your Mac's Music folder using the command line | Main | How to Make Go Programs Generic »
Tuesday
Feb082011

Screwtape Letter #32: Is Go a Functional Programming Language?

My Beloved Wormwood,

I was delighted to find that you're learning about concurrent programming. It was excellent news that your headmaster decided to allow multi-core CPUs in His Eminence's data center. We are certainly the benefactors of less expensive computers, and the work to limit tithing paid to churches shows promise. You'll find answers to you questions below.

Sincerely,


Uncle Screwtape

The Screwtape Letters were written by C.S. Lewis in 1942. They are hillarious and thought provoking at the same time.

 

Is Go a functional programming language?

No. Absolutely not. This assertion is completely ridiculous.

 

Does Go offer functions?

Of course Go has functions. Most programming language offer functions. Oh, you don’t believe me? I’ll show you.

func SayHello() {
    fmt.Println("Hello")
}

 

There. I just wrote a simple function in Go. Just type the key word “func” and specify a name for it.  I called my function “SayHello” because that’s what it does. After the function name you have to specify its input parameters inside parenthesis. My function doesn’t require any input parameters so I just typed an empty set of parenthesis. Finally, you must add the logic of the function inside a set of brackets.

Can Go functions accept arguments?

Well, I see this idiotic line of questioning continues. Oh I understand, programming is not immediately intuitive, so I’ll explain.

func SayHelloToSomeone(name string) {
    fmt.Println("Hello " + name + ".")
}

 

Yes, functions in Go can accept arguments. As you can see, I changed our SayHello function to be a bit more personal. It now accepts a name, presumably a patient, then responds by saying hello to that patient via the console.

Can Go functions return a value?

Yes, yes, yes! Just like in math. Remember Slipslop’s lectures on faith and function? A function such as f(x) = x + 2 would add 2 to the value of x. Let’s build upon our first function. I’ll make a new function called GetGreeting that will return a string.

func GetGreeting (name string) string {
   greeting := "Hello " + name + "."
   return greeting
}

greeting := GetGreeting("Bob")
fmt.Println(greeting) //outputs "Hello Bob."

 

You can also declare the name of the variable to be returned by the function in the function declaration itself. This gives you a couple of things for free. First, you won’t have to re-declare the variable in the function body. Second, you don’t have to specify the variable name after the return statement. The function will implicitly return the said variable in its last known state.

func GetGreeting (name string) (greeting string) {
   greeting = "Hello " + name + "."
   return
}

greeting := GetGreeting("Bob")
fmt.Println(greeting) //outputs "Hello Bob."


Can Go functions accept a function?

Well, I see you’re starting to pay attention. We might just make a programmer out of you yet. Wouldn’t it be nice to say hello to a list of patients you’d like to torment?

Let’s make a struct called TormentList that is composed of a slice of patients. A slice is similar to an array.

type TormentList struct {
    patients []string
}

func NewTormentList(people []string) *TormentList {
   return &TormentList{people}
}

 

Now lets quietly, without disturbing any functional programmers, attach a method to TormentList which will apply a function to each item in the slice.

func (g *TormentList) Map(f func(string)) {
   for _, val := range(g.patients) {
       f(val)
   }
}

 

Map’s single argument is a function f, which accepts a string, and returns nothing. This function iterates over TormentList’s patients, applying the function to each blessed soul in the process. Why don’t we try this out?

patients := []string{"Anand", "David", "Ivan", "JoJo", "Jin", "Mon", "Peter", "Sachin"}

gl := NewTormentList(patients)
gl.Map(SayHelloToSomeone)

/*
outputs the following:

Hello Anand.
Hello David.
Hello Ivan.
Hello JoJo.
Hello Jin.
Hello Mon.
Hello Peter.
Hello Sachin.
*/

 

Can Go functions return a function?

My beloved Wormwood, you’re walking a fine line between an imperative programming and a functional programming. I’ll dismiss this reckless abandon once. But you must swear to keep this example to yourself. Under no circumstance should Joe Armstrong, our mortal enemy and creator of Erlang, discover this.

Let’s discuss a real world scenario. As you know we like to help The Department of Homeland Security impede the plans of American travelers. Just the other day, I saw a security guard discover day old sushimi in a tourist’s pocket. He confiscated the tuna fish and ate it immediately. That’s when I thought of using Go to screen travellers who had recently eaten sushi. This will help security guards fish out spoiled tuna to eat, which will surely lead to indigestion problems and subsequent longer processing times.

func Screen(patients []string) func(string) bool {
   return func(name string) bool {
       for _, soul := range patients {
           if soul == name {
               return true
           }
       }
       return false
   }
}

 

Now that we have a function, we can make a list of all patients who used their credit card to purchase sushi within the last 24 hours.

those_who_bought_sushi := []string{"Anand", "JoJo", "Jin", "Mon", "Peter", "Sachin"}

 

Now we can pass our list of patients to the Screen function and, in turn, receive a “Bought Sushi?” detector.

bought_sushi := Screen(those_who_bought_sushi)

fmt.Println(bought_sushi("Anand")) // true
fmt.Println(bought_sushi("Alex")) // false

 

Go enables us to do work in one paradigm, while under the guise of another. Like us, it's wonderfully deceptive. 

PrintView Printer Friendly Version

EmailEmail Article to Friend

Reader Comments (17)

When you said:

func (g *TormentList) Map(f(func(string))) {

I think you meant


func (g *TormentList) Map(f func(string)) {

February 9, 2011 | Unregistered CommenterFranz

Franz,

Thank you for the code fix!

Charles

February 9, 2011 | Registered CommenterCharles Thompson

Extremely useful writeup, left me asking for more!!..

February 9, 2011 | Unregistered CommenterSEO services

Cool post on the useful codes. I am not good at these so I totally appreciate the information learned from you. Thanks.

Adeel Chowdhry
SalesLetters Creator

February 28, 2011 | Unregistered CommenterAdeel Chowdhry

Does Go offer Tail Recursion?

Whoops, no.

March 6, 2011 | Unregistered Commenterfoo

Adeel, are you sure that gccgo doesn't provide tail recursion? Is there a reason why Go doesn't have tail recursion other than it simply hasn't been implemented yet?

March 9, 2011 | Unregistered CommenterReuben

I really enjoyed the quality information you offer to your visitors for this blog.I will bookmark your blog. This website is also pretty good:
Raymond Weil perfect clone watches

March 31, 2011 | Unregistered CommenterDaivy Smith

Let’s discuss a real pandora jewelry world scenario. As you know we like to help The Department of Homeland Security impede the plans of thomas sabo online shop American travelers. Just the other day, I saw a security guard discover day old thomas sabo charms sushimi in a tourist’s pocket. He confiscated the tuna fish and ate it immediately. That’s when I thought of using Go to screen travellers who had recently eaten sushi. This thomas sabo bracelets will help security guards fish out spoiled tuna to eat, which will surely lead to indigestion meizitang slimming problems and subsequent longer processing times.

All these ideas are quite easy to understand and I wonder why I've never thought thus. It's excellent that your blog is full of worthy information for your readers.
food recipes

November 17, 2011 | Unregistered Commenterterry

By the way Go interfaces do not participate in a type hierarchy like Java's. They are better described as a set of methods, identified by their name and signature.
professional essay writing service

December 13, 2011 | Unregistered Commenterbaster

Programming Language is the base of all knowledge! Thanks a lot for this post!

December 23, 2011 | Unregistered Commenterargument paper topics

If you are interested in purchasing a fake rolex Daytona II, how would you make out whether you are choosing an original or plainly a fake? Considered as the knowledge in relation to imported brands and costly rolex DateJust replica this kind of seeing as replica rolex Milgauss in India.

January 2, 2012 | Unregistered Commenterbranasd

With this particular fashion bangle neighborhood, each and every single men and women has truly restricted itinerary as well as they've really a reduced quantity of adequate time to spend on the getting the may the reason the rings jewelry desires all of us to clearly show into it and also take supreme benefit of it by deciding on the accurate diamond jewellery for the meant ones. Happiness certainly is the principal interest of fashion earrings when it comes to the shoppers.

January 5, 2012 | Unregistered Commenteralssdh

If you should are interested in buying a cheap fake rolex Daytona II watches, how would you make outdoors whether you're purchasing an original or basically a fake? Considered as the recognition concerning imported brands along with costly cheap fake rolex Yachtmaster watches this kind of considered as cheap replica rolex Masterpiece watches in India.

January 7, 2012 | Unregistered Commenteroncernsfh

I think all these ideas are quite easy to understand and I wonder why I've never thought thus.
uk essay writing

January 8, 2012 | Unregistered Commenterterry

Programming language is very necessary now time!

Thank you for hosting your site here can really find a lot of information interestno only wish - for more information would be a practical plan

site

February 6, 2012 | Unregistered Commenterstaralex76

PostPost a New Comment

Enter your information below to add a new comment.

My response is on my own website »
Author Email (optional):
Author URL (optional):
Post:
 
Some HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>