Functions
Higher-order functions
= functions that take one or more functions as arguments or return a function as a result.
package main
import (
"fmt"
)
func power(fn func(int) int) func(int) int { // <--- high-order function
return func(x int) int {
return fn(x)
}
}
func square(x int) int {
return x * x
}
func cube(x int) int {
return x * x * x
}
func main() {
squareFunc := power(square)
cubeFunc := power(cube)
fmt.Println(squareFunc(2)) // Output: 4
fmt.Println(cubeFunc(2)) // Output: 8
}Anonymous functions/Closures/Lambda Functions
= functions that are defined and called in the same place, without a name. They retain bindings to variables defined outside the body of the closure.
Monads
= design pattern that allows us to chain operations together in a pipeline, while abstracting away the details of how the operations are performed. Has 3 components:
Type Constructor (
T): A type that represents a computational context. It wraps a value and provides a way to apply functions to that value while preserving the context.Unit Function (
unitorreturn): A function that takes a value and wraps it in the monadic context, creating a new instance of the monad.Bind Function (
flatMap,chain,>>=): A function that takes a monad and a function that maps a value to a new monad. It applies the function to the value inside the monad and returns a new monad.
Functors
= objects or data structures that can be mapped over, meaning you can apply a function to each element within the functor.
= superclass of a monad, which means that all monads are functors as well.
= design pattern that represents a container or structure that can be mapped over. In functional programming, a functor is often used to apply a function to each element of a collection and return a new collection with the transformed elements.
Monoids
= data types that have two key properties: associativity and an identity element.
Associativity: For all values
a,b, andcof the same type,(a mappend b) mappend cshould be equal toa mappend (b mappend c), wheremappendrepresents the operation.Identity Element: There exists an element (usually denoted as
mempty) such that for any valueaof the same type,mempty mappend ais equal toaanda mappend memptyis equal toa.
Last updated
Was this helpful?