GithubHelp home page GithubHelp logo

ibm / fp-go Goto Github PK

View Code? Open in Web Editor NEW
1.6K 18.0 45.0 6.92 MB

functional programming library for golang

License: Apache License 2.0

Go 99.97% Batchfile 0.03%
functional-programming go golang library monad utility

fp-go's Introduction

Functional programming library for golang

🚧 Work in progress! 🚧 Despite major version 1 because of semantic-release/semantic-release#1507. Trying to not make breaking changes, but devil is in the details.

logo

This library is strongly influenced by the awesome fp-ts.

Getting started

go get github.com/IBM/fp-go

Refer to the samples.

Find API documentation here

Design Goal

This library aims to provide a set of data types and functions that make it easy and fun to write maintainable and testable code in golang. It encourages the following patterns:

  • write many small, testable and pure functions, i.e. functions that produce output only depending on their input and that do not execute side effects
  • offer helpers to isolate side effects into lazily executed functions (IO)
  • expose a consistent set of composition to create new functions from existing ones
    • for each data type there exists a small set of composition functions
    • these functions are called the same across all data types, so you only have to learn a small number of function names
    • the semantic of functions of the same name is consistent across all data types

How does this play with the 🧘🏽 Zen Of Go?

🧘🏽 Each package fulfils a single purpose

βœ”οΈ Each of the top level packages (e.g. Option, Either, ReaderIOEither, ...) fulfils the purpose of defining the respective data type and implementing the set of common operations for this data type.

🧘🏽 Handle errors explicitly

βœ”οΈ The library makes a clear distinction between that operations that cannot fail by design and operations that can fail. Failure is represented via the Either type and errors are handled explicitly by using Either's monadic set of operations.

🧘🏽 Return early rather than nesting deeply

βœ”οΈ We recommend to implement simple, small functions that implement one feature and that would typically not invoke other functions. Interaction with other functions is done by function composition and the composition makes sure to run one function after the other. In the error case the Either monad makes sure to skip the error path.

🧘🏽 Leave concurrency to the caller

βœ”οΈ All pure are synchronous by default. The I/O operations are asynchronous per default.

🧘🏽 Before you launch a goroutine, know when it will stop

🀷🏽 This is left to the user of the library since the library itself will not start goroutines on its own. The Task monad offers support for cancellation via the golang context, though.

🧘🏽 Avoid package level state

βœ”οΈ No package level state anywhere, this would be a significant anti-pattern

🧘🏽 Simplicity matters

βœ”οΈ The library is simple in the sense that it offers a small, consistent interface to a variety of data types. Users can concentrate on implementing business logic rather than dealing with low level data structures.

🧘🏽 Write tests to lock in the behaviour of your package’s API

🟑 The programming pattern suggested by this library encourages writing test cases. The library itself also has a growing number of tests, but not enough, yet. TBD

🧘🏽 If you think it’s slow, first prove it with a benchmark

βœ”οΈ Absolutely. If you think the function composition offered by this library is too slow, please provide a benchmark.

🧘🏽 Moderation is a virtue

βœ”οΈ The library does not implement its own goroutines and also does not require any expensive synchronization primitives. Coordination of IO operations is implemented via atomic counters without additional primitives.

🧘🏽 Maintainability counts

βœ”οΈ Code that consumes this library is easy to maintain because of the small and concise set of operations exposed. Also the suggested programming paradigm to decompose an application into small functions increases maintainability, because these functions are easy to understand and if they are pure, it's often sufficient to look at the type signature to understand the purpose.

The library itself also comprises many small functions, but it's admittedly harder to maintain than code that uses it. However this asymmetry is intended because it offloads complexity from users into a central component.

Comparison to Idiomatic Go

In this section we discuss how the functional APIs differ from idiomatic go function signatures and how to convert back and forth.

Pure functions

Pure functions are functions that take input parameters and that compute an output without changing any global state and without mutating the input parameters. They will always return the same output for the same input.

Without Errors

If your pure function does not return an error, the idiomatic signature is just fine and no changes are required.

With Errors

If your pure function can return an error, then it will have a (T, error) return value in idiomatic go. In functional style the return value is Either[error, T] because function composition is easier with such a return type. Use the EitherizeXXX methods in "github.com/IBM/fp-go/either" to convert from idiomatic to functional style and UneitherizeXXX to convert from functional to idiomatic style.

Effectful functions

An effectful function (or function with a side effect) is one that changes data outside the scope of the function or that does not always produce the same output for the same input (because it depends on some external, mutable state). There is no special way in idiomatic go to identify such a function other than documentation. In functional style we represent them as functions that do not take an input but that produce an output. The base type for these functions is IO[T] because in many cases such functions represent I/O operations.

Without Errors

If your effectful function does not return an error, the functional signature is IO[T]

With Errors

If your effectful function can return an error, the functional signature is IOEither[error, T]. Use EitherizeXXX from "github.com/IBM/fp-go/ioeither" to convert an idiomatic go function to functional style.

Go Context

Functions that take a context are per definition effectful because they depend on the context parameter that is designed to be mutable (it can e.g. be used to cancel a running operation). Furthermore in idiomatic go the parameter is typically passed as the first parameter to a function.

In functional style we isolate the context and represent the nature of the effectful function as an IOEither[error, T]. The resulting type is ReaderIOEither[T], a function taking a context that returns a function without parameters returning an Either[error, T]. Use the EitherizeXXX methods from "github.com/IBM/fp-go/context/readerioeither" to convert an idiomatic go function with a context to functional style.

Implementation Notes

Generics

All monadic operations are implemented via generics, i.e. they offer a type safe way to compose operations. This allows for convenient IDE support and also gives confidence about the correctness of the composition at compile time.

Downside is that this will result in different versions of each operation per type, these versions are generated by the golang compiler at build time (unlike type erasure in languages such as Java of TypeScript). This might lead to large binaries for codebases with many different types. If this is a concern, you can always implement type erasure on top, i.e. use the monadic operations with the any type as if generics were not supported. You loose type safety, but this might result in smaller binaries.

Ordering of Generic Type Parameters

In go we need to specify all type parameters of a function on the global function definition, even if the function returns a higher order function and some of the type parameters are only applicable to the higher order function. So the following is not possible:

func Map[A, B any](f func(A) B) [R, E any]func(fa ReaderIOEither[R, E, A]) ReaderIOEither[R, E, B]

Note that the parameters R and E are not needed by the first level of Map but only by the resulting higher order function. Instead we need to specify the following:

func Map[R, E, A, B any](f func(A) B) func(fa ReaderIOEither[R, E, A]) ReaderIOEither[R, E, B]

which overspecifies Map on the global scope. As a result the go compiler will not be able to auto-detect these parameters, it can only auto detect A and B since they appear in the argument of Map. We need to explicitly pass values for these type parameters when Map is being used.

Because of this limitation the order of parameters on a function matters. We want to make sure that we define those parameters that cannot be auto-detected, first, and the parameters that can be auto-detected, last. This can lead to inconsistencies in parameter ordering, but we believe that the gain in convenience is worth it. The parameter order of Ap is e.g. different from that of Map:

func Ap[B, R, E, A any](fa ReaderIOEither[R, E, A]) func(fab ReaderIOEither[R, E, func(A) B]) ReaderIOEither[R, E, B]

because R, E and A can be determined from the argument to Ap but B cannot.

Use of the ~ Operator

The FP library attempts to be easy to consume and one aspect of this is the definition of higher level type definitions instead of having to use their low level equivalent. It is e.g. more convenient and readable to use

ReaderIOEither[R, E, A]

than

func(R) func() Either.Either[E, A]

although both are logically equivalent. At the time of this writing the go type system does not support generic type aliases, only generic type definition, i.e. it is not possible to write:

type ReaderIOEither[R, E, A any] = RD.Reader[R, IOE.IOEither[E, A]]

only

type ReaderIOEither[R, E, A any] RD.Reader[R, IOE.IOEither[E, A]]

This makes a big difference, because in the second case the type ReaderIOEither[R, E, A any] is considered a completely new type, not compatible to its right hand side, so it's not just a shortcut but a fully new type.

From the implementation perspective however there is no reason to restrict the implementation to the new type, it can be generic for all compatible types. The way to express this in go is the ~ operator. This comes with some quite complicated type declarations in some cases, which undermines the goal of the library to be easy to use.

For that reason there exist sub-packages called Generic for all higher level types. These packages contain the fully generic implementation of the operations, preferring abstraction over usability. These packages are not meant to be used by end-users but are meant to be used by library extensions. The implementation for the convenient higher level types specializes the generic implementation for the particular higher level type, i.e. this layer does not contain any business logic but only type magic.

Higher Kinded Types

Go does not support higher kinded types (HKT). Such types occur if a generic type itself is parametrized by another generic type. Example:

The Map operation for ReaderIOEither is defined as:

func Map[R, E, A, B any](f func(A) B) func(fa ReaderIOEither[R, E, A]) ReaderIOEither[R, E, B]

and in fact the equivalent operations for all other monads follow the same pattern, we could try to introduce a new type for ReaderIOEither (without a parameter) as a HKT, e.g. like so (made-up syntax, does not work in go):

func Map[HKT, R, E, A, B any](f func(A) B) func(HKT[R, E, A]) HKT[R, E, B]

this would be the completely generic method signature for all possible monads. In particular in many cases it is possible to compose functions independent of the concrete knowledge of the actual HKT. From the perspective of a library this is the ideal situation because then a particular algorithm only has to be implemented and tested once.

This FP library addresses this by introducing the HKTs as individual types, e.g. HKT[A] would be represented as a new generic type HKTA. This loses the correlation to the type A but allows to implement generic algorithms, at the price of readability.

For that reason these implementations are kept in the internal package. These are meant to be used by the library itself or by extensions, not by end users.

Map/Ap/Flap

The following table lists the relationship between some selected operators

Operator Parameter Monad Result
Map func(A) B HKT[A] HKT[B]
Chain func(A) HKT[B] HKT[A] HKT[B]
Ap HKT[A] HKT[func(A)B] HKT[B]
Flap A HKT[func(A)B] HKT[B]

fp-go's People

Contributors

a-lipson avatar carstenleue avatar elliotchenzichang avatar francistm avatar ibm-open-source-bot avatar jdbaldry avatar laglangyue avatar olira avatar pinguo-lixin avatar renovate[bot] avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

fp-go's Issues

Help w/ Functional Wrapping

Hello Dr Carsten,

I was working on a project, and I encountered a function that I wanted to try to wrap into a function into a IOEither type.

The function's signature looks like this:

package docconv

func ConvertDocx(r io.Reader) (string, map[string]string, error)

docconv.ConvertDocx :: io.Reader -> IOEither error (string, (string -> string))

So, this is my attempt at a wrapper for the function.

// wrapper function
func convertDocx(r io.Reader) IOE.IOEither[error, T.Tuple2[string, map[string]string]] {

	text, meta, err := docconv.ConvertDocx(r)
	if err != nil {
		return IOE.Left[T.Tuple2[string, map[string]string]](err)
	}

	return IOE.Right[error](T.MakeTuple2(text, meta))
}

However, I was wondering if it's possible to more concisely convert a function with more than one output parameter into a function that returns a tuple of those parameters. I'd imagine this is very similar to the TupledN functions, but just for the function outputs.
Does this functionality exist in fp-go? If not, is there a reason why?

Of course, even if this functionality is available, functions that have more than one input and more than one output at the same time are still difficult to work with.

To illustrate,

func OutTupled3[F ~func(T) (R1, R2, R3), T, R1 R2, R3 any](f F) func(T) Tuple3[R1, R2, R3] {
    return func(t T) Tuple3[R1, R2, R3] {
        t1, t2, t3 := f(t)        
        return T.MakeTuple3[t1, t2, t3]
    }
}

The next part of the use case doesn't really make sense anywhere aside from functions that throw some arguments and then an error, where the either-ness is implicit in the function definition that all other outputs are going to be invalid (even if, perhaps they were initialized to some value aside from their zero value).
A counterexample is perhaps an IO function with a couple steps, where side effects could occur even when the ultimate return value of the function is an error.

Nonetheless, now we must convert the tuple which, at this point, contains an error as it's last element, and convert it into a IOEither that contains the error as the left argument, and then the remaining size N-1 tuple as the right argument.
I suppose these functions could be named EitherizeN or IOEitherizeN?
The choice of where to put the selected field is not particularly consequential because there are Swap functions for the Either types.


The second question I have is related to converting between Either[A, B] and Option[B]. My specific case is with, IOEither[error, []byte] and Option[error].

I'm trying to create a function which takes a string path and a bytes slice content using ioeither/file.WriteFile(path, os.ModePerm) and the function in creates, and then returns an Option[error] in the case that the IOEither[error, []byte] had a value in the left side.

I have tried both the ioeither.Fold and ioeither.GetOrElse methods and am currently looking at your examples in context/readerioeither and either/examples_extract_test to see if I can figure it out.

What I've landed on thus far is an io.IO[error], which I don't think I can get out of unless the original type was Either[error, IO[[]byte]].

err := F.Pipe3(
	content, 
	IOF.WriteFile(path, os.ModePerm),
	IOE.Swap, 
	IOE.GetOrElse(F.Constant1[[]byte](IO.Of[error](nil))),
)

So, my question is, how might you solve this problem. My hope is that the solution is rather elegant and I'm overcomplicating the problem by having taken an erroneous approach from the get-go.

Thank you very much once again!

Learning fp-go question

Hello!

I'm currently in the process of learning fp-go and am aiming to apply functional programming principles in Go. To get hands-on experience, I've taken a straightforward task: rewriting a Go function that initializes a NATS JetStream connection and subsequently creates multiple streams.

Here's the original code for context:

func Fx(lc fx.Lifecycle, natsConn *nats.Conn) FX {
	lc.Append(fx.Hook{OnStart: func(ctx context.Context) error {
		js, err := jetstream.New(natsConn)
		if err != nil {
			return err
		}
		if err = GetCreateEventsStream(ctx, js); err != nil {
			return err
		}
		if err = GetCreateAlertsStream(ctx, js); err != nil {
			return err
		}
		if err = GetCreateDLQStream(ctx, js); err != nil {
			return err
		}
		return nil
	}})
	return FX{}
}

Could someone guide me on the idiomatic way to rewrite this function using fp-go? I'm looking for a functional approach that would align with the paradigms and best practices of the library.

Thank you!

Questions & Comments on differences between Pipe and Flow

fp-go/function/gen.go

Lines 27 to 40 in 45e05f2

// Pipe1 takes an initial value t0 and successively applies 1 functions where the input of a function is the return value of the previous function
// The final return value is the result of the last function application
func Pipe1[F1 ~func(T0) T1, T0, T1 any](t0 T0, f1 F1) T1 {
t1 := f1(t0)
return t1
}
// Flow1 creates a function that takes an initial value t0 and successively applies 1 functions where the input of a function is the return value of the previous function
// The final return value is the result of the last function application
func Flow1[F1 ~func(T0) T1, T0, T1 any](f1 F1) func(T0) T1 {
return func(t0 T0) T1 {
return Pipe1(t0, f1)
}
}

I have been following this guide to fp-ts which you linked to in your article on the IO Monad in Go
I am reading the part about the difference between pipes and flows.

The author, Ryan, notes that the difference in the function signature between pipes and flows is that one operates on a value as the initial term while the other operates on a function.

pipes: A -> (A->B) -> (B->C) -> (C->D)
flows: (A->B) -> (B->C) -> (C->D) -> (D->E)

Can we abstract values to be a function that goes from no value to A?
Borrowing the Unit type from Haskell, ()->A
This satisfies the function signature of the flow composition in that the Unit to A function ()->A, matches the A->B type as the initial value of the flow.

I suppose that this would just lead to excessive syntax in go.
Unlike in Haskell, where let x = 42 as a value is syntactically more verbose than its function counterpart x = 42 which takes no inputs.

// define a value
x := 42

Pipe(x, f1, f2, ...)

// define a function that takes Unit and returns a value
f := func() int { return 42 } 

Flow(f, f1, f2, ...)

In addition, in terms of usage, it seems like creating a flow is a composition tool which allows one to build more complex functions from simple ones, whereas pipe is used for the actual evaluation. So, I can see the difference in use case between the two functions.

However, from the standpoint of reducing complexity, given that we cannot overload nor are we being able to use variadics for n input functions, reducing the PipeN or FlowN would be ideal.

I suppose one could write,

input := 42 
output := FlowN(f1, f2, ...)(input)

But that breaks left-to-right readability where we can have

input := 42
output := PipeN(input, f1, f2, ...)

A different question I have, relating to generics, is the importance of the type parameter order
for example, in this function signature, there are two functions with two output types. These output types are set at the end to be any.
Is there a particular reason for defining the function signature types first and then the other (value?) types?

fp-go/function/gen.go

Lines 87 to 93 in 45e05f2

// Flow2 creates a function that takes an initial value t0 and successively applies 2 functions where the input of a function is the return value of the previous function
// The final return value is the result of the last function application
func Flow2[F1 ~func(T0) T1, F2 ~func(T1) T2, T0, T1, T2 any](f1 F1, f2 F2) func(T0) T2 {
return func(t0 T0) T2 {
return Pipe2(t0, f1, f2)
}
}

for example,

func Flow2[T0, T1, T2 any, F1 ~func(T0) T1, F2 ~func(T1) T2](f1 F1, f2 F2) func(T0) T2

My guess would be that either, a) it's good convention to leave the plainly any types at the end of the type parameter bit, or b) F comes before T in the alphabet.
I haven't done much work with go generics in the past, so I am unfamiliar with the convention. I think that both ways of defining the signature are legible, but, again, I was wondering if there was a particular reason.

answered the above with another look at the readme.

Lastly, I look hope that generics for methods in go will one day be added so that we can introduce bind and not have to worry about Pipe100!

http/request header issue

First of all, ty for your articles and hard work on the lib - it's awesome.

I'm struggling to get my head around "how to change the request header" using http/request funcs.
Normally I would do:

type headerFunc func(*http.Request) *http.Request

var (
    headers = map[string]headerFunc{
        "text": contentTypeText,
})

func contentTypeText(req *http.Request) *http.Request{
    req.Header.Set("Content-Type", "text/html")
return req
}

func MakeHeaderWithMap (req *http.Request, headerText string) *http.Request{
   if setHeader, ok := headers[headerText]; ok{
      return setHeader(req)}
  panic("header not supported")
}

In your sample ur making a "MakeGetRequest", but I failed to access the Requester's Header and change it...
Any hint/Advice would be highly appreceited.

Ty in advance.

missing Match function on Either type

I wander how can I handle the either type, say in the main function I want to print the error and exit if val is left or log the value if it is right, can we introduce a Match function in Either ? Or there is better way to do that?

func main() {
  name := GetName(NewThing("hello"))
// Match on Either
  Match(name,
    func(err error) {
	    log.Fatal("failed err %v \n", err)
    },
    func(val string) {
	    fmt.Printf("get val %s \n", val)
    },
  )
}

func Match[T any, V any](e E.Either[T, V], l func(t T), r func(v V)) {
	a, b := E.Unwrap(e)
	if E.IsLeft(e) {
		l(b)
	} else {
		r(a)
	}
}

func GetName(val O.Option[Thing]) E.Either[error, string] {
	return O.Fold(
		F.Constant[E.Either[error, string]](E.Left[string](errors.New("val is none"))),
		getName,
	)(val)
}

func getName(val Thing) E.Either[error, string] {
	if val.Name == "" {
		return E.Left[string](errors.New("name is not empty"))
	}
	return E.Right[error](val.Name)
}

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

This repository currently has no open or pending branches.

Detected dependencies

github-actions
.github/workflows/build.yml
  • actions/checkout v4.1.7@692973e3d937129bcbf40652eb9f2f61becf3332
  • actions/setup-go v5
  • actions/checkout v4.1.7@692973e3d937129bcbf40652eb9f2f61becf3332
  • actions/setup-node v4.0.3@1e60f620b9541d16bece96c5465dc8ee9832be0b
  • actions/setup-go v5
gomod
go.mod
  • github.com/stretchr/testify v1.9.0
  • github.com/urfave/cli/v2 v2.27.4

  • Check this box to trigger a request for Renovate to run again on this repository

Would a function family like `BindNofVariadic()` be useful? | Chaining w/ inheritance

Please forgive me for creating this issue for creating this issue if this functionality is already possible with a composition of extant functions.

Nonetheless, let me describe the scenario I am working with.

I have a function from a library that takes a single variadic input. I have a pipeline of functions that eventually needs to put an item into this variadic function.

The current approach that I am taking is to pipe up to the last function and store that output, then to pass the output to the the library's function.

I have also taken a look at using the Unvariadic0 function, but I think the method above is simpler.

This leads me to wonder if functions that would take functions with variadic arguments and produce functions with a finite set of arguments would be helpful.

While looking for a way to accomplish this, I found the bind and ignore functions which are similar, but I don't fully understand them. Hence why I imagined that there probably exists a way to accomplish what I was trying to accomplish, yet I cannot see it.

I might implement the BindNofVariadic function like this,

func Bind1ofVariadic[T, R any](f func(...T) R) func(T) R {
    return func(t T) R {
        return f(t)
    }
}

Then for two arguments,

func Bind2ofVariadic[T, R any](f func(...T1) R) func(T, T) R {
    return func(t1, t2 T) R {
        return f(t1, t2)
    }
}

One potential consideration would be the case where a function has its variadic argument in the second, third, fourth, etc. position. As is the case with the UnvariadicN family of functions.

The minimal differences between Bind1..., Bind2... and BindN... suggest to me now that this functionality might be accomplished by some form of UnvariadicN and then some sort of indexing of the resulting slice.
For example, if there were a family of slice builder functions from some data, like FromN, then one could go from the single value to a From1 to a Unvariadic0 on some function f. However, I think this might be just another version of the same proposed solution.

Or perhaps this problem is indicative of some inherent design issue, rather than reason for a new function.


Another question that I have is about how chaining with inherited types works.

Here are two examples that I created to try to better understand.

type MyString string

// need to define a cast method
func (m MyString) String() string { return string(m) }

func TestCastingInPipeline() {

	var text MyString = "hi"

	uppercase := strings.ToUpper
	cast := MyString.String

	out1 := F.Pipe2(text, cast, uppercase)

	out2a := uppercase(cast(text))
	out2b := uppercase(string(text)) // works without cast method

	// assert.Equal(t, out1, out2a, out2b)
}

and

type Thing interface {
	Do() int
}

type MyType struct{}

// make MyType implement Thing
func (m MyType) Do() int { return 1 }

func ThingAction(thing Thing) int { return thing.Do() }

func TestInheritancePipeline() {

	example := MyType{}

	// MyType implements Thing but type of MyType != type of Thing
	out1 := F.Pipe1(example, ThingAction)

	// MyType implements Thing
	out2 := ThingAction(example)

	// assert.Equal(t, out1, out2)

}

Aside from this, I am enjoying trying to implement functional design patterns in my go project.
I am following the tutorials that you have linked (both Ryan Lee's blog and Professor Frisby's Mostly Adequate Guide to Functional Programming)
In addition, I am trying to learn Haskell and Category Theory (mainly following Bartosz Milewski's lectures on YouTube at the moment) to have a better understanding of the functional concepts before employing them in go.

Thank you very much for this resource and assistance!

onleft error return nil panics

Hi @CarstenLeue

if I try to return nil for the Jar property of a cookie, if it's creation fails, the code panics. Setting it to nil directly is working (see client creation comments)
Is my assumption wrong that the onErrorJar function sets "jar to nil"?
Is there an idomatic way of dealing with this?

import (
	"errors"
	"fmt"
	H "github.com/IBM/fp-go/context/readerioeither/http"
	"github.com/IBM/fp-go/either"
	F "github.com/IBM/fp-go/function"
	"golang.org/x/net/publicsuffix"
	"net/http"
	"net/http/cookiejar"
)

func main() {
	onErrorJar := func(e error) *cookiejar.Jar {
		return nil
	}
	jar := F.Pipe1(
		makeMaybeJar(),
		either.GetOrElse(onErrorJar),
	)
	client := F.Pipe1(
		&http.Client{Jar: jar}, // fails
		//&http.Client{Jar: nil}, //  works
		H.MakeClient,
	)
	fmt.Print(client)

}

type jarBuilder struct{}

func JarBuilder() jarBuilder {
	return jarBuilder{}
}

func (b jarBuilder) Build() either.Either[error, *cookiejar.Jar] {
	return either.TryCatchError(func() (*cookiejar.Jar, error) {
		jar, err := cookiejar.New(&cookiejar.Options{PublicSuffixList: publicsuffix.List})
		err = errors.New("fail on purpose")
		return jar, err
	})
}

func makeMaybeJar() either.Either[error, *cookiejar.Jar] {
	return JarBuilder().Build()
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.