fp-ts简介 - 第一部分

Function composition is an important concept in FP. It is the idea that small, simple functions can be composed together to create larger, more sophisticated functions. fp-ts has a couple of helper functions that let us do this – flow and pipe.

函数组合是FP中的一个重要概念。它是指小的、简单的函数可以被组合在一起以创建更大的、更复杂的函数。FP-TS有几个辅助函数让我们这样做--flowpipe

flow

流动

The documentation for flow says it “performs left-to-right function composition”. Let’s dig into that.

flow 的文档说它 "执行从左到右的函数组合"。让我们深入了解一下。

Let’s say we have some functions:

比方说,我们有一些函数:

If we wanted to call these three functions in order – clean, len, double – then it might look something like this:

如果我们想按顺序调用这三个函数--clean、len、double--那么它可能看起来像这样:

To read this, you have to read the code inside out which isn’t great. flow creates a function that calls the given functions in order. eg:

要读懂这个,你必须从里到外读懂代码,这不是很好。flow ,创建一个函数,按顺序调用给定的函数。例如:

This is called function composition. It has composed the three functions into one. It takes the output of each function and passes it as the argument to the next. You would call it like this:

这就是所谓的函数组合。它将三个函数组成了一个。它将每个函数的输出作为参数传递给下一个函数。你会这样称呼它:

flow has some restrictions on the functions that can be passed to it arguments. The first function can have any number of arguments, the rest must take only a single argument (ie: have an arity of one – unary).

flow 对可以传递给它的参数的函数有一些限制。第一个函数可以有任何数量的参数,其余的必须只接受一个参数(即:有一个arity - 单数)。

pipe

管道

The documentation for pipe says it “pipes the value of an expression into a pipeline of functions”. What does that mean though?

pipe 的文档说它 "将表达式的值输送到一个函数管道中"。但这是什么意思呢?

We’ll reuse the same functions as before:

我们将重复使用与之前相同的函数:

The difference between pipe and flow is that the pipe takes a value (or an expression, since every expression returns a value) as the first argument. You would call it like this:

pipeflow 之间的区别是,pipe 将一个值(或一个表达式,因为每个表达式都会返回一个值)作为第一个参数。你可以这样调用它:

The initial value is passed as the argument to first function. The output of that function is then passed as the argument of the next function and so on, in the same ...

开通本站会员,查看完整译文。

首页 - Wiki
Copyright © 2011-2024 iteam. Current version is 2.123.1. UTC+08:00, 2024-03-29 23:53
浙ICP备14020137号-1 $访客地图$