[Solved] Functional programming in JS


I’m assuming that you’re familiar with Haskell since you’re using Haskell idioms. You have the following functions:

getLine :: () -> IO String -- why isn't this simply `getLine :: IO String`?
cat :: String -> Task Error String

The first thing you want to do is get rid of the superfluous function wrapping the IO action:

getLine () :: IO String

Then, you can use fmap to compose cat and getLine ():

fmap cat getLine () :: IO (Task Error String)

Finally, assuming Task is analogous to Either and fork is analogous to either we can do:

fmap cat getLine () >>= fork logError printResult :: IO String

This can be written in JavaScript as follows:

getLine()
    .map(cat)
    .bind(fork(logError, printResult));

Now, all you need to do is implement the appropriate map and bind methods for IO actions in JavaScript.


Edit: To compose them you could simply do the following in Haskell:

(>>= fork logError printResult) . fmap cat . getLine :: () -> IO String

In JavaScript this would translate to:

compose( bind(fork(logError, printResult))
       , fmap(cat)
       , getLine
       );

This assumes that fmap and bind are defined as follows:

function fmap(f) {
    return function (x) {
        return x.map(f);
    };
}

function bind(f) {
    return function (x) {
        return x.bind(f);
    };
}

Hence, you still need to implement the map and bind methods for IO actions.

4

solved Functional programming in JS