fpGo

package module
v1.1.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 20, 2018 License: MIT Imports: 8 Imported by: 0

README

fpGo

tag Go Report Card GoDoc

license stars forks

Monad, Functional Programming features for Golang

Why

I love functional programing, Rx-style coding, and Optional usages.

However it's hard to implement them in Golang, and there're few libraries to achieve parts of them.

Thus I implemented fpGo. I hope you would like it :)

Features

  • Optional

  • Maybe

  • Publisher

  • Pattern matching

  • Fp functions

  • Java8Stream-like Collection

  • PythonicGenerator-like Coroutine(yield/yieldFrom)

Usage

Optional (IsPresent/IsNil, Or, Let)

var m MaybeDef
var orVal int
var boolVal bool

// IsPresent(), IsNil()
m = Maybe.Just(1)
boolVal = m.IsPresent() // true
boolVal = m.IsNil() // false
m = Maybe.Just(nil)
boolVal = m.IsPresent() // false
boolVal = m.IsNil() // true

// Or()
m = Maybe.Just(1)
fmt.Println((m.Or(3))) // 1
m = Maybe.Just(nil)
fmt.Println((m.Or(3))) // 3

// Let()
var letVal int
letVal = 1
m = Maybe.Just(1)
m.Let(func() {
  letVal = 2
})
fmt.Println(letVal) // letVal would be 2

letVal = 1
m = Maybe.Just(nil)
m.Let(func() {
  letVal = 3
})
fmt.Println(letVal) // letVal would be still 1

MonadIO (RxObserver-like)

Example:

var m *MonadIODef
var actualInt int

m = MonadIO.Just(1)
actualInt = 0
m.Subscribe(Subscription{
  OnNext: func(in interface{}) {
    actualInt, _ = Maybe.Just(in).ToInt()
  },
})
fmt.Println(actualInt) // actualInt would be 1

m = MonadIO.Just(1).FlatMap(func(in interface{}) *MonadIODef {
  v, _ := Maybe.Just(in).ToInt()
  return MonadIO.Just(v + 1)
})
actualInt = 0
m.Subscribe(Subscription{
  OnNext: func(in interface{}) {
    actualInt, _ = Maybe.Just(in).ToInt()
  },
})
fmt.Println(actualInt) // actualInt would be 2

Stream (inspired by Collection libs)

Example:

var s *StreamDef
var tempString = ""

s = Stream.FromArrayInt([]int{}).Append(1).Extend(Stream.FromArrayInt([]int{2, 3, 4})).Extend(Stream.FromArray([]interface{}{nil}))
tempString = ""
for _, v := range s.ToArray() {
  tempString += Maybe.Just(v).ToMaybe().ToString()
}
fmt.Println(tempString) // tempString would be "1234<nil>"
s = s.Distinct()
tempString = ""
for _, v := range s.ToArray() {
  tempString += Maybe.Just(v).ToMaybe().ToString()
}
fmt.Println(tempString) // tempString would be "1234"

Compose

Example:

var fn01 = func(args ...interface{}) []interface{} {
  val, _ := Maybe.Just(args[0]).ToInt()
  return SliceOf(val + 1)
}
var fn02 = func(args ...interface{}) []interface{} {
  val, _ := Maybe.Just(args[0]).ToInt()
  return SliceOf(val + 2)
}
var fn03 = func(args ...interface{}) []interface{} {
  val, _ := Maybe.Just(args[0]).ToInt()
  return SliceOf(val + 3)
}

// Result would be 6
result := Compose(fn01, fn02, fn03)((0))[0]

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Compose

func Compose(fnList ...func(...interface{}) []interface{}) func(...interface{}) []interface{}

Compose Compose the functions from right to left (Math: f(g(x)) Compose: Compose(f, g)(x))

func Either

func Either(value interface{}, patterns ...Pattern) interface{}

Either Match Pattern list and return the effect() result of the matching Pattern

func MatchCompType

func MatchCompType(compType CompType, value CompData) bool

MatchCompType Check does the Composite Data match the given SumType

func MatchCompTypeRef

func MatchCompTypeRef(compType CompType, value *CompData) bool

MatchCompTypeRef Check does the Composite Data match the given SumType

func PtrOf

func PtrOf(v interface{}) *interface{}

PtrOf Return Ptr of a value

func SliceOf added in v1.1.3

func SliceOf(args ...interface{}) []interface{}

SliceOf Return Ptr of a value

Types

type AtomBool

type AtomBool struct {
	// contains filtered or unexported fields
}

AtomBool Atomic Bool

func (*AtomBool) Get

func (atomBoolSelf *AtomBool) Get() bool

Get Get the bool atomically

func (*AtomBool) Set

func (atomBoolSelf *AtomBool) Set(value bool)

Set Set the bool atomically

type CompData

type CompData struct {
	// contains filtered or unexported fields
}

CompData Composite Data with values & its CompType(SumType)

func NewCompData

func NewCompData(compType CompType, value ...interface{}) *CompData

NewCompData New SumType Data by its type and composite values

type CompType

type CompType interface {
	Matches(value ...interface{}) bool
}

CompType Abstract SumType concept interface

func DefProduct

func DefProduct(kinds ...reflect.Kind) CompType

DefProduct Define the ProductType of a SumType

func DefSum

func DefSum(compTypes ...CompType) CompType

DefSum Define the SumType by CompType list

type CompTypePatternDef

type CompTypePatternDef struct {
	// contains filtered or unexported fields
}

CompTypePatternDef Pattern which matching when the SumType matches

func (CompTypePatternDef) Apply

func (patternSelf CompTypePatternDef) Apply(value interface{}) interface{}

Apply Evaluate the result by its given effect function

func (CompTypePatternDef) Matches

func (patternSelf CompTypePatternDef) Matches(value interface{}) bool

Matches Match the given value by the pattern

type CorDef

type CorDef struct {
	// contains filtered or unexported fields
}

CorDef Cor Coroutine inspired by Python/Ecmascript/Lua

var Cor CorDef

Cor Cor utils instance

func (*CorDef) DoNotation

func (corSelf *CorDef) DoNotation(effect func(*CorDef) interface{}) interface{}

DoNotation Do Notation by function (inspired by Haskell one)

func (*CorDef) IsDone

func (corSelf *CorDef) IsDone() bool

IsDone Is the Cor done

func (*CorDef) IsStarted

func (corSelf *CorDef) IsStarted() bool

IsStarted Is the Cor started

func (*CorDef) New

func (corSelf *CorDef) New(effect func()) *CorDef

New New a Cor instance

func (*CorDef) NewAndStart

func (corSelf *CorDef) NewAndStart(effect func()) *CorDef

NewAndStart New a Cor instance and start it immediately

func (*CorDef) Start

func (corSelf *CorDef) Start()

Start Start the Cor

func (*CorDef) StartWithVal added in v1.1.0

func (corSelf *CorDef) StartWithVal(in interface{})

StartWithVal Start the Cor with an initial value

func (*CorDef) Yield

func (corSelf *CorDef) Yield() interface{}

Yield Yield back(nil)

func (*CorDef) YieldFrom

func (corSelf *CorDef) YieldFrom(target *CorDef, in interface{}) interface{}

YieldFrom Yield from a given Cor

func (*CorDef) YieldFromIO

func (corSelf *CorDef) YieldFromIO(target *MonadIODef) interface{}

YieldFromIO Yield from a given MonadIO

func (*CorDef) YieldRef

func (corSelf *CorDef) YieldRef(out interface{}) interface{}

YieldRef Yield a value

type CorOp

type CorOp struct {
	// contains filtered or unexported fields
}

CorOp Cor Yield Operation/Delegation/Callback

type CurryDef

type CurryDef struct {
	// contains filtered or unexported fields
}

CurryDef Curry inspired by Currying in Java ways

var Curry CurryDef

Curry Curry utils instance

func (*CurryDef) Call

func (currySelf *CurryDef) Call(args ...interface{}) *CurryDef

Call Call the currying function by partial or all args

func (*CurryDef) IsDone

func (currySelf *CurryDef) IsDone() bool

IsDone Is the currying done

func (*CurryDef) MarkDone

func (currySelf *CurryDef) MarkDone()

MarkDone Mark the currying is done(let others know it)

func (*CurryDef) New

func (currySelf *CurryDef) New(fn func(c *CurryDef, args ...interface{}) interface{}) *CurryDef

New New Curry instance by function

func (*CurryDef) Result

func (currySelf *CurryDef) Result() interface{}

Result Get the result value of currying

type EqualPatternDef

type EqualPatternDef struct {
	// contains filtered or unexported fields
}

EqualPatternDef Pattern which matching when the given object is equal to predefined one

func (EqualPatternDef) Apply

func (patternSelf EqualPatternDef) Apply(value interface{}) interface{}

Apply Evaluate the result by its given effect function

func (EqualPatternDef) Matches

func (patternSelf EqualPatternDef) Matches(value interface{}) bool

Matches Match the given value by the pattern

type HandlerDef

type HandlerDef struct {
	// contains filtered or unexported fields
}

HandlerDef Handler inspired by Android/WebWorker

var Handler HandlerDef

Handler Handler utils instance

func (*HandlerDef) Close

func (handlerSelf *HandlerDef) Close()

Close Close the Handler

func (*HandlerDef) GetDefault

func (handlerSelf *HandlerDef) GetDefault() *HandlerDef

GetDefault Get Default Handler

func (*HandlerDef) New

func (handlerSelf *HandlerDef) New() *HandlerDef

New New Handler instance

func (*HandlerDef) NewByCh

func (handlerSelf *HandlerDef) NewByCh(ioCh *chan func()) *HandlerDef

NewByCh New Handler by its Channel

func (*HandlerDef) Post

func (handlerSelf *HandlerDef) Post(fn func())

Post Post a function to execute on the Handler

type KindPatternDef

type KindPatternDef struct {
	// contains filtered or unexported fields
}

KindPatternDef Pattern which matching when the kind matches

func (KindPatternDef) Apply

func (patternSelf KindPatternDef) Apply(value interface{}) interface{}

Apply Evaluate the result by its given effect function

func (KindPatternDef) Matches

func (patternSelf KindPatternDef) Matches(value interface{}) bool

Matches Match the given value by the pattern

type MaybeDef

type MaybeDef struct {
	// contains filtered or unexported fields
}

MaybeDef Maybe inspired by Rx/Optional/Guava/Haskell

var Maybe MaybeDef

Maybe Maybe utils instance

func (MaybeDef) Clone added in v1.1.1

func (maybeSelf MaybeDef) Clone() MaybeDef

Clone Clone Maybe object & its wrapped value

func (MaybeDef) CloneTo added in v1.1.1

func (maybeSelf MaybeDef) CloneTo(dest interface{}) MaybeDef

CloneTo Clone the Ptr target to an another Ptr target

func (MaybeDef) FlatMap

func (maybeSelf MaybeDef) FlatMap(fn func(interface{}) *MaybeDef) *MaybeDef

FlatMap FlatMap Maybe by function

func (MaybeDef) IsKind

func (maybeSelf MaybeDef) IsKind(t reflect.Kind) bool

IsKind Check is its Kind equal to the given one

func (MaybeDef) IsNil

func (maybeSelf MaybeDef) IsNil() bool

IsNil Check is it nil

func (MaybeDef) IsPresent

func (maybeSelf MaybeDef) IsPresent() bool

IsPresent Check is it present(not nil)

func (MaybeDef) IsType

func (maybeSelf MaybeDef) IsType(t reflect.Type) bool

IsType Check is its Type equal to the given one

func (MaybeDef) IsValid added in v1.1.0

func (maybeSelf MaybeDef) IsValid() bool

IsValid Check is its reflect.ValueOf(ref) valid

func (MaybeDef) Just

func (maybeSelf MaybeDef) Just(in interface{}) MaybeDef

Just New Maybe by a given value

func (MaybeDef) Kind

func (maybeSelf MaybeDef) Kind() reflect.Kind

Kind Get its Kind

func (MaybeDef) Let

func (maybeSelf MaybeDef) Let(fn func())

Let If the wrapped value is not nil, then do the given function

func (MaybeDef) Or

func (maybeSelf MaybeDef) Or(or interface{}) interface{}

Or Check the value wrapped by Maybe, if it's nil then return a given fallback value

func (MaybeDef) ToBool

func (maybeSelf MaybeDef) ToBool() (bool, error)

ToBool Maybe to Bool

func (MaybeDef) ToFloat32

func (maybeSelf MaybeDef) ToFloat32() (float32, error)

ToFloat32 Maybe to Float32

func (MaybeDef) ToFloat64

func (maybeSelf MaybeDef) ToFloat64() (float64, error)

ToFloat64 Maybe to Float64

func (MaybeDef) ToInt

func (maybeSelf MaybeDef) ToInt() (int, error)

ToInt Maybe to Int

func (MaybeDef) ToInt32

func (maybeSelf MaybeDef) ToInt32() (int32, error)

ToInt32 Maybe to Int32

func (MaybeDef) ToInt64

func (maybeSelf MaybeDef) ToInt64() (int64, error)

ToInt64 Maybe to Int64

func (MaybeDef) ToMaybe

func (maybeSelf MaybeDef) ToMaybe() MaybeDef

ToMaybe Maybe to Maybe

func (MaybeDef) ToPtr added in v1.1.0

func (maybeSelf MaybeDef) ToPtr() *interface{}

ToPtr Maybe to Ptr

func (MaybeDef) ToString

func (maybeSelf MaybeDef) ToString() string

ToString Maybe to String

func (MaybeDef) Type

func (maybeSelf MaybeDef) Type() reflect.Type

Type Get its Type

func (MaybeDef) Unwrap

func (maybeSelf MaybeDef) Unwrap() interface{}

Unwrap Unwrap the wrapped value of Maybe

type MonadIODef

type MonadIODef struct {
	// contains filtered or unexported fields
}

MonadIODef MonadIO inspired by Rx/Observable

var MonadIO MonadIODef

MonadIO MonadIO utils instance

func (*MonadIODef) FlatMap

func (monadIOSelf *MonadIODef) FlatMap(fn func(interface{}) *MonadIODef) *MonadIODef

FlatMap FlatMap the MonadIO by function

func (MonadIODef) Just

func (monadIOSelf MonadIODef) Just(in interface{}) *MonadIODef

Just New MonadIO by a given value

func (*MonadIODef) New

func (monadIOSelf *MonadIODef) New(effect func() interface{}) *MonadIODef

New New MonadIO by effect function

func (*MonadIODef) ObserveOn

func (monadIOSelf *MonadIODef) ObserveOn(h *HandlerDef) *MonadIODef

ObserveOn Observe the MonadIO on the specific Handler

func (*MonadIODef) Subscribe

func (monadIOSelf *MonadIODef) Subscribe(s Subscription) *Subscription

Subscribe Subscribe the MonadIO by Subscription

func (*MonadIODef) SubscribeOn

func (monadIOSelf *MonadIODef) SubscribeOn(h *HandlerDef) *MonadIODef

SubscribeOn Subscribe the MonadIO on the specific Handler

type NilTypeDef

type NilTypeDef struct {
}

NilTypeDef NilType implemented by Nil determinations

var NilType NilTypeDef

NilType NilType CompType instance

func (NilTypeDef) Matches

func (typeSelf NilTypeDef) Matches(value ...interface{}) bool

Matches Check does it match nil

type OtherwisePatternDef

type OtherwisePatternDef struct {
	// contains filtered or unexported fields
}

OtherwisePatternDef Pattern which matching when the others didn't match(finally)

func (OtherwisePatternDef) Apply

func (patternSelf OtherwisePatternDef) Apply(value interface{}) interface{}

Apply Evaluate the result by its given effect function

func (OtherwisePatternDef) Matches

func (patternSelf OtherwisePatternDef) Matches(value interface{}) bool

Matches Match the given value by the pattern

type Pattern

type Pattern interface {
	Matches(value interface{}) bool
	Apply(interface{}) interface{}
}

Pattern Pattern general interface

func InCaseOfEqual

func InCaseOfEqual(value interface{}, effect fnObj) Pattern

InCaseOfEqual In case of its value is equal to the given one

func InCaseOfKind

func InCaseOfKind(kind reflect.Kind, effect fnObj) Pattern

InCaseOfKind In case of its Kind matches the given one

func InCaseOfRegex

func InCaseOfRegex(pattern string, effect fnObj) Pattern

InCaseOfRegex In case of the given regex rule matches its value

func InCaseOfSumType

func InCaseOfSumType(compType CompType, effect fnObj) Pattern

InCaseOfSumType In case of its SumType matches the given one

func Otherwise

func Otherwise(effect fnObj) Pattern

Otherwise In case of the other patterns didn't match it

type PatternMatching

type PatternMatching struct {
	// contains filtered or unexported fields
}

PatternMatching PatternMatching contains Pattern list

func DefPattern

func DefPattern(patterns ...Pattern) PatternMatching

DefPattern Define the PatternMatching by Pattern list

func (PatternMatching) MatchFor

func (patternMatchingSelf PatternMatching) MatchFor(inValue interface{}) interface{}

MatchFor Check does the given value match anyone of the Pattern list of PatternMatching

type ProductType

type ProductType struct {
	// contains filtered or unexported fields
}

ProductType ProductType with a Kind list

func (ProductType) Matches

func (typeSelf ProductType) Matches(value ...interface{}) bool

Matches Check does it match the ProductType

type PublisherDef

type PublisherDef struct {
	// contains filtered or unexported fields
}

PublisherDef Publisher inspired by Rx/NotificationCenter/PubSub

var Publisher PublisherDef

Publisher Publisher utils instance

func (*PublisherDef) Map

func (publisherSelf *PublisherDef) Map(fn func(interface{}) interface{}) *PublisherDef

Map Map the Publisher in order to make a broadcasting chain

func (*PublisherDef) New

func (publisherSelf *PublisherDef) New() *PublisherDef

New New a Publisher

func (*PublisherDef) Publish

func (publisherSelf *PublisherDef) Publish(result interface{})

Publish Publish a value to its subscribers or next chains

func (*PublisherDef) Subscribe

func (publisherSelf *PublisherDef) Subscribe(sub Subscription) *Subscription

Subscribe Subscribe the Publisher by Subscription

func (*PublisherDef) SubscribeOn

func (publisherSelf *PublisherDef) SubscribeOn(h *HandlerDef) *PublisherDef

SubscribeOn Subscribe the Publisher on the specific Handler

func (*PublisherDef) Unsubscribe

func (publisherSelf *PublisherDef) Unsubscribe(s *Subscription)

Unsubscribe Unsubscribe the publisher by the Subscription

type RegexPatternDef

type RegexPatternDef struct {
	// contains filtered or unexported fields
}

RegexPatternDef Pattern which matching when the regex rule matches the given string

func (RegexPatternDef) Apply

func (patternSelf RegexPatternDef) Apply(value interface{}) interface{}

Apply Evaluate the result by its given effect function

func (RegexPatternDef) Matches

func (patternSelf RegexPatternDef) Matches(value interface{}) bool

Matches Match the given value by the pattern

type StreamDef

type StreamDef struct {
	// contains filtered or unexported fields
}

StreamDef Stream inspired by Collection utils

var Stream StreamDef

Stream Stream utils instance

func (*StreamDef) Append

func (streamSelf *StreamDef) Append(item interface{}) *StreamDef

Append Append an item into Stream

func (*StreamDef) Distinct

func (streamSelf *StreamDef) Distinct() *StreamDef

Distinct Filter not nil items and return a new Stream instance

func (*StreamDef) Extend

func (streamSelf *StreamDef) Extend(stream *StreamDef) *StreamDef

Extend Extend Stream by an another Stream

func (*StreamDef) Filter

func (streamSelf *StreamDef) Filter(fn func(int) bool) *StreamDef

Filter Filter items of Stream by function

func (*StreamDef) FromArray

func (streamSelf *StreamDef) FromArray(list []interface{}) *StreamDef

FromArray New Stream instance from an interface{} array

func (*StreamDef) FromArrayBool

func (streamSelf *StreamDef) FromArrayBool(old []bool) *StreamDef

FromArrayBool New Stream instance from a bool array

func (*StreamDef) FromArrayFloat32

func (streamSelf *StreamDef) FromArrayFloat32(old []float32) *StreamDef

FromArrayFloat32 New Stream instance from a float32 array

func (*StreamDef) FromArrayFloat64

func (streamSelf *StreamDef) FromArrayFloat64(old []float64) *StreamDef

FromArrayFloat64 New Stream instance from a float64 array

func (*StreamDef) FromArrayInt

func (streamSelf *StreamDef) FromArrayInt(old []int) *StreamDef

FromArrayInt New Stream instance from an int array

func (*StreamDef) FromArrayInt32

func (streamSelf *StreamDef) FromArrayInt32(old []int32) *StreamDef

FromArrayInt32 New Stream instance from an int32 array

func (*StreamDef) FromArrayInt64

func (streamSelf *StreamDef) FromArrayInt64(old []int64) *StreamDef

FromArrayInt64 New Stream instance from an int64 array

func (*StreamDef) FromArrayMaybe

func (streamSelf *StreamDef) FromArrayMaybe(old []MaybeDef) *StreamDef

FromArrayMaybe FromArrayMaybe New Stream instance from a Maybe array

func (*StreamDef) FromArrayString

func (streamSelf *StreamDef) FromArrayString(old []string) *StreamDef

FromArrayString New Stream instance from a string array

func (*StreamDef) Get

func (streamSelf *StreamDef) Get(i int) interface{}

Get Get an item of Stream by its index

func (*StreamDef) Len

func (streamSelf *StreamDef) Len() int

Len Get length of Stream

func (*StreamDef) Map

func (streamSelf *StreamDef) Map(fn func(int) interface{}) *StreamDef

Map Map all items of Stream by function

func (*StreamDef) Remove

func (streamSelf *StreamDef) Remove(index int) *StreamDef

Remove Remove an item by its index

func (*StreamDef) Sort

func (streamSelf *StreamDef) Sort(fn func(i, j int) bool) *StreamDef

Sort Sort Stream items by function

func (*StreamDef) ToArray

func (streamSelf *StreamDef) ToArray() []interface{}

ToArray Convert Stream to slice

type Subscription

type Subscription struct {
	OnNext func(interface{})
}

Subscription the delegation/callback of MonadIO/Publisher

type SumType

type SumType struct {
	// contains filtered or unexported fields
}

SumType SumType contains a CompType list

func (SumType) Matches

func (typeSelf SumType) Matches(value ...interface{}) bool

Matches Check does it match the SumType

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL