Skip to content

Instantly share code, notes, and snippets.

@donvito
Last active November 26, 2019 14:05
Show Gist options
  • Save donvito/37e56f1eb07ba15a3e770e078f285e8a to your computer and use it in GitHub Desktop.
Save donvito/37e56f1eb07ba15a3e770e078f285e8a to your computer and use it in GitHub Desktop.
Higher order functions
package main
import (
"fmt"
)
func balanceFormula(paidLate bool) func(float64, float64) float64 {
if(paidLate == true){
fn := func(principal float64, lateFee float64) float64{
balance := principal + lateFee
return balance
}
return fn
}else{
fn := func(principal float64, lateFee float64) float64{
//balance := principal
return principal
}
return fn
}
}
func main() {
principal := 1000.00
lateFee := 50.00
formula := balanceFormula(false)
balance := formula(principal, lateFee)
fmt.Println(balance)
}
package main
import (
"fmt"
)
type CustomerAccount struct{
Name string
PaidLate bool
Principal float64
LateFee float64
}
func balanceFormula(paidLate bool) func(float64, float64) float64 {
if(paidLate == true){
fn := func(principal float64, lateFee float64) float64{
balance := principal + lateFee
return balance
}
return fn
}else{
fn := func(principal float64, lateFee float64) float64{
return principal
}
return fn
}
}
func main() {
//late payment
customer1 := CustomerAccount{"Melvin", true, 1000.00, 50.00}
//payment is on-time
customer2 := CustomerAccount{"Dave", false, 1000.00, 50.00}
fmt.Printf("Customer balance of customer %s is %f\n", customer1.Name, balanceFormula(customer1.PaidLate)(customer1.Principal, customer1.LateFee))
fmt.Printf("Customer balance of customer %s is %f", customer2.Name, balanceFormula(customer2.PaidLate)(customer2.Principal, customer2.LateFee))
}
package main
import (
"fmt"
)
func operate(x int, y int, operator func(x int, y int) int) int{
return operator(x,y)
}
func main() {
x := 10
y := 5
adder := func(x int, y int) int{
return x + y
}
subtractor := func(x int, y int) int{
return x - y
}
fmt.Println(operate(x, y, adder))
fmt.Println(operate(x, y, subtractor))
}
package main
import (
"fmt"
)
type MyFile struct{
Name string
Base64 string
}
func main() {
myFile := MyFile{"test.pdf", "base64 encoded file"}
s3 := func(file MyFile) bool{
fmt.Printf("\nSaving %s file implementation to S3", file.Name)
return true
}
blob := func(file MyFile) bool{
fmt.Printf("\nSaving %s file to blob storage", file.Name)
return true
}
fs := func(file MyFile) bool{
fmt.Printf("\nSaving %s file to disk", file.Name)
return true
}
processSave(myFile, s3)
processSave(myFile, blob)
processSave(myFile, fs)
}
func processSave(file MyFile, save func(file MyFile) bool){
save(file)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment