• Stars
    star
    1,480
  • Rank 30,571 (Top 0.7 %)
  • Language
    Go
  • License
    Apache License 2.0
  • Created 10 months ago
  • Updated about 2 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

functional programming library for golang

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

Opertator 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]

More Repositories

1

sarama

Sarama is a Go library for Apache Kafka.
Go
10,858
star
2

plex

The package of IBM’s typeface, IBM Plex.
CSS
9,297
star
3

css-gridish

Automatically build your grid design’s CSS Grid code, CSS Flexbox fallback code, Sketch artboards, and Chrome extension.
CSS
2,253
star
4

openapi-to-graphql

Translate APIs described by OpenAPI Specifications (OAS) into GraphQL
TypeScript
1,594
star
5

Project_CodeNet

This repository is to support contributions for tools for the Project CodeNet dataset hosted in DAX
Python
1,485
star
6

pytorch-seq2seq

An open source framework for seq2seq models in PyTorch.
Python
1,431
star
7

fhe-toolkit-linux

IBM Fully Homomorphic Encryption Toolkit For Linux. This toolkit is a Linux based Docker container that demonstrates computing on encrypted data without decrypting it! The toolkit ships with two demos including a fully encrypted Machine Learning inference with a Neural Network and a Privacy-Preserving key-value search.
C++
1,427
star
8

ibm.github.io

IBM Open Source at GitHub
JavaScript
1,106
star
9

MicroscoPy

An open-source, motorized, and modular microscope built using LEGO bricks, Arduino, Raspberry Pi and 3D printing.
Python
1,102
star
10

Dromedary

Dromedary: towards helpful, ethical and reliable LLMs.
Python
1,059
star
11

MAX-Image-Resolution-Enhancer

Upscale an image by a factor of 4, while generating photo-realistic details.
Python
863
star
12

elasticsearch-spark-recommender

Use Jupyter Notebooks to demonstrate how to build a Recommender with Apache Spark & Elasticsearch
Jupyter Notebook
806
star
13

differential-privacy-library

Diffprivlib: The IBM Differential Privacy Library
Python
774
star
14

build-blockchain-insurance-app

Sample insurance application using Hyperledger Fabric
JavaScript
719
star
15

FfDL

Fabric for Deep Learning (FfDL, pronounced fiddle) is a Deep Learning Platform offering TensorFlow, Caffe, PyTorch etc. as a Service on Kubernetes
Go
676
star
16

spring-boot-microservices-on-kubernetes

In this code we demonstrate how a simple Spring Boot application can be deployed on top of Kubernetes. This application, Office Space, mimicks the fictitious app idea from Michael Bolton in the movie "Office Space".
JavaScript
548
star
17

cloud-native-starter

Cloud Native Starter for Java/Jakarta EE based Microservices on Kubernetes and Istio
Shell
517
star
18

federated-learning-lib

A library for federated learning (a distributed machine learning process) in an enterprise environment.
Python
480
star
19

nicedoc.io

pretty README as service.
JavaScript
473
star
20

clai

Command Line Artificial Intelligence or CLAI is an open-sourced project from IBM Research aimed to bring the power of AI to the command line interface.
Python
466
star
21

import-tracker

Python utility for tracking third party dependencies within a library
Python
458
star
22

mac-ibm-enrollment-app

The Mac@IBM enrollment app makes setting up macOS with Jamf Pro more intuitive for users and easier for IT. The application offers IT admins the ability to gather additional information about their users during setup, allows users to customize their enrollment by selecting apps or bundles of apps to install during setup, and provides users with next steps when enrollment is complete.
Swift
454
star
23

mobx-react-router

Keep your MobX state in sync with react-router
JavaScript
437
star
24

openapi-validator

Configurable and extensible validator/linter for OpenAPI documents
JavaScript
429
star
25

EvolveGCN

Code for EvolveGCN: Evolving Graph Convolutional Networks for Dynamic Graphs
Python
384
star
26

fhe-toolkit-macos

IBM Homomorphic Encryption Toolkit For MacOS
C++
356
star
27

AutoMLPipeline.jl

A package that makes it trivial to create and evaluate machine learning pipeline architectures.
HTML
345
star
28

graphql-query-generator

Randomly generates GraphQL queries from a GraphQL schema
TypeScript
334
star
29

portieris

A Kubernetes Admission Controller for verifying image trust.
Go
329
star
30

BluePic

WARNING: This repository is no longer maintained ⚠️ This repository will not be updated. The repository will be kept available in read-only mode.
Swift
325
star
31

FedMA

Code for Federated Learning with Matched Averaging, ICLR 2020.
Python
320
star
32

lale

Library for Semi-Automated Data Science
Python
320
star
33

powerai-counting-cars

Run a Jupyter Notebook to detect, track, and count cars in a video using Maximo Visual Insights (formerly PowerAI Vision) and OpenCV
Jupyter Notebook
317
star
34

evote

A voting application that leverages Hyperledger Fabric and the IBM Blockchain Platform to record and tally ballots.
JavaScript
316
star
35

aihwkit

IBM Analog Hardware Acceleration Kit
Jupyter Notebook
314
star
36

zshot

Zero and Few shot named entity & relationships recognition
Python
308
star
37

blockchain-network-on-kubernetes

Demonstrates the steps involved in setting up your business network on Hyperledger Fabric using Kubernetes APIs on IBM Cloud Kubernetes Service.
Shell
305
star
38

IBM-Z-zOS

The helpful and handy location for finding and sharing z/OS files, which are not included in the product.
REXX
296
star
39

charts

The IBM/charts repository provides helm charts for IBM and Third Party middleware.
Smarty
295
star
40

TabFormer

Code & Data for "Tabular Transformers for Modeling Multivariate Time Series" (ICASSP, 2021)
Python
295
star
41

blockchain-application-using-fabric-java-sdk

Create and Deploy a Blockchain Network using Hyperledger Fabric SDK Java
Java
292
star
42

mac-ibm-notifications

macOS agent used to display custom notifications and alerts to the end user.
Swift
289
star
43

MAX-Object-Detector

Localize and identify multiple objects in a single image.
Python
286
star
44

design-kit

The IBM Design kit is a collection of tools aimed to help you design and prototype experiences faster, with confidence and thoughtfulness. This kit is based on the IBM Design System. Also, you may use this documentation to create add-on libraries to the IBM Design System or submit bugs to the current system.
272
star
45

AccDNN

A compiler from AI model to RTL (Verilog) accelerator in FPGA hardware with auto design space exploration.
Verilog
270
star
46

deploy-ibm-cloud-private

Instructions and Code required to install IBM Cloud Private
HCL
263
star
47

vue-a11y-calendar

Accessible, internationalized Vue calendar
JavaScript
253
star
48

audit-ci

Audit NPM, Yarn, and PNPM dependencies in continuous integration environments, preventing integration if vulnerabilities are found at or above a configurable threshold while ignoring allowlisted advisories
TypeScript
253
star
49

watson-banking-chatbot

A chatbot for banking that uses the Watson Assistant, Discovery, Natural Language Understanding and Tone Analyzer services.
JavaScript
250
star
50

UQ360

Uncertainty Quantification 360 (UQ360) is an extensible open-source toolkit that can help you estimate, communicate and use uncertainty in machine learning model predictions.
Python
249
star
51

Kubernetes-container-service-GitLab-sample

This code shows how a common multi-component GitLab can be deployed on Kubernetes cluster. Each component (NGINX, Ruby on Rails, Redis, PostgreSQL, and more) runs in a separate container or group of containers.
Shell
243
star
52

tensorflow-hangul-recognition

Handwritten Korean Character Recognition with TensorFlow and Android
Python
232
star
53

transition-amr-parser

SoTA Abstract Meaning Representation (AMR) parsing with word-node alignments in Pytorch. Includes checkpoints and other tools such as statistical significance Smatch.
Python
229
star
54

BlockchainNetwork-CompositeJourney

Part 1 in a series of patterns showing the building blocks of a Blockchain application
Shell
227
star
55

pytorchpipe

PyTorchPipe (PTP) is a component-oriented framework for rapid prototyping and training of computational pipelines combining vision and language
Python
223
star
56

Graph2Seq

Graph2Seq is a simple code for building a graph-encoder and sequence-decoder for NLP and other AI/ML/DL tasks.
Python
219
star
57

LNN

A `Neural = Symbolic` framework for sound and complete weighted real-value logic
Python
214
star
58

Scalable-WordPress-deployment-on-Kubernetes

This code showcases the full power of Kubernetes clusters and shows how can we deploy the world's most popular website framework on top of world's most popular container orchestration platform.
Shell
214
star
59

janusgraph-utils

Develop a graph database app using JanusGraph
Java
204
star
60

ModuleFormer

ModuleFormer is a MoE-based architecture that includes two different types of experts: stick-breaking attention heads and feedforward experts. We released a collection of ModuleFormer-based Language Models (MoLM) ranging in scale from 4 billion to 8 billion parameters.
Python
203
star
61

ibm-generative-ai

IBM-Generative-AI is a Python library built on IBM's large language model REST interface to seamlessly integrate and extend this service in Python programs.
Python
202
star
62

tensorflow-large-model-support

Large Model Support in Tensorflow
199
star
63

Scalable-Cassandra-deployment-on-Kubernetes

In this code we provide a full roadmap the deployment of a multi-node scalable Cassandra cluster on Kubernetes. Cassandra understands that it is running within a cluster manager, and uses this cluster management infrastructure to help implement the application. Kubernetes concepts like Replication Controller, StatefulSets etc. are leveraged to deploy either non-persistent or persistent Cassandra clusters on Kubernetes cluster.
Shell
195
star
64

adaptive-federated-learning

Code for paper "Adaptive Federated Learning in Resource Constrained Edge Computing Systems"
Python
193
star
65

action-recognition-pytorch

This is the pytorch implementation of some representative action recognition approaches including I3D, S3D, TSN and TAM.
Python
193
star
66

gantt-chart

IBM Gantt Chart Component, integrable in Vanilla, jQuery, or React Framework.
JavaScript
193
star
67

api-samples

Samples code that uses QRadar API's
Python
192
star
68

cdfsl-benchmark

(ECCV 2020) Cross-Domain Few-Shot Learning Benchmarking System
Python
190
star
69

kube101

Kubernetes 101 workshop (https://ibm.github.io/kube101/)
Shell
184
star
70

CrossViT

Official implementation of CrossViT. https://arxiv.org/abs/2103.14899
Python
180
star
71

browser-functions

A lightweight serverless platform that uses Web Browsers as execution engines
JavaScript
180
star
72

pwa-lit-template

A template for building Progressive Web Applications using Lit and Vaadin Router.
TypeScript
176
star
73

rl-testbed-for-energyplus

Reinforcement Learning Testbed for Power Consumption Optimization using EnergyPlus
Python
170
star
74

AMLSim

The AMLSim project is intended to provide a multi-agent based simulator that generates synthetic banking transaction data together with a set of known money laundering patterns - mainly for the purpose of testing machine learning models and graph algorithms. We welcome you to enhance this effort since the data set related to money laundering is critical to advance detection capabilities of money laundering activities.
Python
170
star
75

socket-io

A Socket.IO client for C#
C#
169
star
76

tfjs-web-app

A TensorFlow.js Progressive Web App for Offline Visual Recognition
JavaScript
164
star
77

molformer

Repository for MolFormer
Jupyter Notebook
163
star
78

spark-tpc-ds-performance-test

Use the TPC-DS benchmark to test Spark SQL performance
TSQL
160
star
79

watson-online-store

Learn how to use Watson Assistant and Watson Discovery. This application demonstrates a simple abstraction of a chatbot interacting with a Cloudant NoSQL database, using a Slack UI.
HTML
156
star
80

istio101

Istio 101 workshop (https://ibm.github.io/istio101/)
Shell
154
star
81

Medical-Blockchain

A healthcare data management platform built on blockchain that stores medical data off-chain
Vue
150
star
82

watson-assistant-slots-intro

A Chatbot for ordering a pizza that demonstrates how using the IBM Watson Assistant Slots feature, one can fill out an order, form, or profile.
JavaScript
143
star
83

tsfm

Foundation Models for Time Series
Jupyter Notebook
143
star
84

simulai

A toolkit with data-driven pipelines for physics-informed machine learning.
Python
142
star
85

etcd-java

Alternative etcd3 java client
Java
141
star
86

deploy-react-kubernetes

Built for developers who are interested in learning how to deploy a React application on Kubernetes, this pattern uses the React and Redux framework and calls the OMDb API to look up movie information based on user input. This pattern can be built and run on both Docker and Kubernetes.
JavaScript
139
star
87

innovate-digital-bank

This repository contains instructions to build a digital bank composed of a set of microservices that communicate with each other. Using Nodejs, Express, MongoDB and deployed to a Kubernetes cluster on IBM Cloud.
JavaScript
137
star
88

ipfs-social-proof

IPFS Social Proof: A decentralized identity and social proof system
JavaScript
135
star
89

KubeflowDojo

Repository to hold code, instructions, demos and pointers to presentation assets for Kubeflow Dojo
Jupyter Notebook
132
star
90

probabilistic-federated-neural-matching

Bayesian Nonparametric Federated Learning of Neural Networks
Python
132
star
91

fhe-toolkit-ios

IBM Fully Homomorphic Encryption Toolkit For iOS
C++
131
star
92

pytorch-large-model-support

Large Model Support in PyTorch
130
star
93

taxinomitis

Source code for Machine Learning for Kids site
JavaScript
127
star
94

Decentralized-Energy-Composer

WARNING: This repository is no longer maintained ⚠️ We are no longer showing the Hyperledger Composer Service.
TypeScript
127
star
95

quantum-careers

Learn about career opportunities with IBM Quantum.
126
star
96

cloud-pak

IBM Cloud Paks are enterprise-grade containerized software by combining container images with enterprise capabilities for deployment in production use cases with integrations for management and lifecycle operations. Features such as pre-configured deployments based on product expertise, rolling upgrades, and management of production workloads.
Shell
126
star
97

build-knowledge-base-with-domain-specific-documents

Create a knowledge base using domain specific documents and the mammoth python library
Jupyter Notebook
125
star
98

japan-technology

IBM Related Japanese technical documents - Code Patterns, Learning Path, Tutorials, etc.
Jupyter Notebook
125
star
99

DiffuseKronA

DiffuseKronA: A Parameter Efficient Fine-tuning Method for Personalized Diffusion Models
125
star
100

compliance-trestle

An opinionated tooling platform for managing compliance as code, using continuous integration and NIST's OSCAL standard.
Python
124
star