Skip to Content
Learning Functional Programming in Go
book

Learning Functional Programming in Go

by Lex Sheehan
November 2017
Intermediate to advanced
670 pages
17h 35m
English
Packt Publishing
Content preview from Learning Functional Programming in Go

Sum base classes

Here are our base classes:

type Int32 int32type Int64 int64type Float32 float32type IntSlice []int

We can see from our type definitions that we will be able to sum any two of these base types.

Here’s the Int32 implementation of Sum:

func (i Int32) Sum(s Sum) int64 {   it := int64(i)   switch x := s.(type) {   case Int64:      return it + int64(x)   case Int32:      return it + int64(x)   case Float32:      return it + int64(x)   case IntSlice:      sum := int64(0)      for _, num := range x {         sum += int64(num)      }      return it + sum   default:      return 0   }}

Notice that we return zero if the value we are trying to add our Int32 to is not in the accepted list of types.

Another option would be to implement a result type, like Haskell’s Either type. This is a recent Golang ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learning Functional Programming

Learning Functional Programming

Jack Widman

Publisher Resources

ISBN: 9781787281394Supplemental Content