简体   繁体   中英

Functional programming in JS

Playing with FP in JS.
Suppose I have 2 functions

getLine :: () -> IO String
cat :: String -> Task Error String

What is the proper way of composing this two functions?

UPD : I can't see any other solution except

const main = () => compose(map(cat), getLine).performIO().fork(logError, printResult)

but I'm not sure that this is proper way of doing it.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM