Giter VIP home page Giter VIP logo

bind_op's Introduction

bind_op

Kind of monadic bind operator for C++

Just have fun with some kind of C++ bind operator from Haskell

The bind operator allow you to apply a function to a monad. For example, Haskell have the Maybe monad which can be in two different states: Just with a value or Nothing which represent the absence of value.

Recently C++ added std::optional to the standard (C++17/1z), you can found it in std::experimental::optional for recent versions of C++14. std::optional is really similar to Haskell's Maybe monad, that's why I wrote this function.

The Bind operator allow you to apply a function to the monad in the case this one contains a value, or return nullopt in the case it contains nothing.

Enough speaking, here is a simple example (let's assume this is C++17):

#include <bind_op>
#include <cassert>
#include <iostream>
#include <optional>

int main() {
  auto opt_1 = std::make_optional(42);
  auto opt_2 = std::make_optional(21);
  auto opt_result = opt_1 >>= [&](const auto& x) {
    return opt_2 >>= [&](const auto& y) {
      return (y + x);
    };
  };
  assert(**opt_result == 63);
}

bind_op's People

Contributors

jeremyletang avatar

Stargazers

 avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

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.