Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding bind function

In this article, the author explains monad using this example (I am guessing Haskell is used):

bind f' :: (Float,String) -> (Float,String)

which implies that

bind :: (Float -> (Float,String)) -> ((Float,String) -> (Float,String))

and proceed to ask to implement the function bind and offer the solution as:

bind f' (gx,gs) = let (fx,fs) = f' gx in (fx,gs++fs)

I am having problem understanding the solution. What would this look like in C or Swift?

I have gone as far as I can implementing the example and I am stuck at implementing bind:

let f: Float -> Float = { value in return 2 * value }
let g: Float -> Float = { value in return 10 + value }

let ff: Float -> (Float, String) = { value in return (f(value), "f called") }
let gg: Float -> (Float, String) = { value in return (g(value), "f called") }
like image 945
Boon Avatar asked Dec 06 '25 15:12

Boon


2 Answers

In C++ I think it would look something like this:

#include <functional>
#include <string>
#include <utility>

using P = std::pair<float, std::string>;
using FP = std::function<P(P)>;

FP mbind(std::function<P(float)> f) {
    return [f](P in) {
        auto && res = f(in.first);
        return {res.first, in.second + res.second};
    };
}

In C you could do something similar by storing function pointers, though the invocation syntax would have to be more verbose since you'll need to pass the state around explicitly.

like image 65
Kerrek SB Avatar answered Dec 08 '25 10:12

Kerrek SB


In Swift, perhaps something like this:

let bind: (Float -> (Float, String)) -> ((Float, String) -> (Float, String)) = { 
    lhs in

    return { 
        rhs in

        let result = lhs(rhs.0)
        return (result.0, "\(result.1); \(rhs.1)" )
    }
}
like image 21
0x416e746f6e Avatar answered Dec 08 '25 09:12

0x416e746f6e



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!