简体   繁体   English

JS中的函数式编程

[英]Functional programming in JS

Playing with FP in JS.在 JS 中玩 FP。
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 UPD :除此之外,我看不到任何其他解决方案

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.我假设您熟悉 Haskell,因为您使用的是 Haskell 习语。 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:您要做的第一件事是摆脱包装 IO 操作的多余函数:

getLine () :: IO String

Then, you can use fmap to compose cat and getLine () :然后,您可以使用fmap组合catgetLine ()

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

Finally, assuming Task is analogous to Either and fork is analogous to either we can do:最后,假设Task类似于Eitherfork类似于我们可以做的either

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

This can be written in JavaScript as follows:这可以用 JavaScript 编写如下:

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.现在,您需要做的就是在 JavaScript 中为 IO 操作实现适当的mapbind方法。


Edit: To compose them you could simply do the following in Haskell:编辑:要编写它们,您只需在 Haskell 中执行以下操作:

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

In JavaScript this would translate to:在 JavaScript 中,这将转换为:

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

This assumes that fmap and bind are defined as follows:这假设fmapbind定义如下:

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.因此,您仍然需要为 IO 操作实现mapbind方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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