函数式编程 模式_函数式编程模式:食谱
函数式编程 模式
This article targets an audience that’s graduating from functional libraries like ramda
to using Algebraic Data Types. We’re using the excellent crocks
library for our ADTs and helpers, although these concepts may apply to other ones as well. We’ll be focusing on demonstrating practical applications and patterns without delving into a lot of theory.
本文面向从ramda
类的功能库毕业到使用代数数据类型的ramda
。 我们正在为ADT和辅助程序使用出色的crocks
库,尽管这些概念也可能适用于其他概念。 我们将专注于演示实际的应用程序和模式,而无需深入研究很多理论。
安全执行危险功能 (Safely Executing Dangerous Functions)
Let’s say we have a situation where we want to use a function called darken
from a third-party library. darken
takes a multiplier, a color and returns a darker shade of that color.
假设有一种情况,我们想使用第三方库中的称为darken
函数。 darken
需要乘数,一种颜色并返回该颜色的较深阴影。
// darken :: Number -> String -> String
darken(0.1)("gray")
//=> "#343434"
Pretty handy for our CSS needs. But it turns out that the function is not as innocent as it seems. darken
throws errors when it receives unexpected arguments!
非常方便满足我们CSS需求。 但事实证明,该功能并不像看起来那样简单。 当它收到意外的参数时, darken
会引发错误!
darken(0.1)(null)
=> // Error: Passed an incorrect argument to a color function, please pass a string representation of a color.
This is, of course, very helpful for debugging — but we wouldn’t want our application to blow up just because we couldn’t derive a color. Here’s where tryCatch
comes to the rescue.
当然,这对于调试非常有帮助-但我们不希望仅由于无法派生颜色而使应用程序崩溃。 这是tryCatch
进行救援的地方。
import { darken } from "polished"
import { tryCatch, compose, either, constant, identity, curry } from "crocks"// safeDarken :: Number -> String -> String
const safeDarken = curry(n =>compose(either(constant("inherit"), identity),tryCatch(darken(n)))
)
tryCatch
executes the provided function within a try-catch block and returns a Sum Type called Result
. In its essence, a Sum Type is basically an “or” type. This means that the Result
could be either an Ok
if an operation is successful or an Error
in case of failures. Other examples of Sum Types include Maybe
, Either
, Async
and so on. The either
point-free helper breaks the value out of the Result
box, and returns the CSS default inherit
if things went south or the darkened color if everything went well.
tryCatch
在try-catch块中执行提供的功能,并返回一个称为Result
的Sum Type。 本质上,Sum类型基本上是“或”类型。 这意味着该Result
可能是任一种Ok
是否操作成功或 Error
的故障的情况下。 Sum类型的其他示例包括Maybe
, Either
, Async
等。 either
点辅助程序都将值从Result
框中分解出来,如果一切向南,则返回CSS默认inherit
如果一切顺利,则返回暗色。
safeDarken(0.5)(null)
//=> inheritsafeDarken(0.25)('green')
//=> '#004d00'
使用Maybe Helpers强制类型 (Enforcing Types using Maybe Helpers)
With JavaScript, we often run into cases where our functions explode because we’re expecting a particular data type, but we receive a different one instead. crocks
provides the safe
, safeAfter
and safeLift
functions that allow us to execute code more predictably by using the Maybe
type. Let’s look at a way to convert camelCased strings into Title Case.
使用JavaScript,我们经常会遇到函数爆炸的情况,因为我们期望的是一种特定的数据类型,但是却收到了另一种数据类型。 crocks
提供safe
, safeAfter
和safeLift
功能,使我们能够使用更多的可预见的执行代码Maybe
类型。 让我们看看一种将驼峰式字符串转换为Title Case的方法。
import { safeAfter, safeLift, isArray, isString, map, compose, option } from "crocks"// match :: Regex -> String -> Maybe [String]
const match = regex => safeAfter(isArray, str => str.match(regex))// join :: String -> [String] -> String
const join = separator => array => array.join(separator)// upperFirst :: String -> String
const upperFirst = x =>x.charAt(0).toUpperCase().concat(x.slice(1).toLowerCase())// uncamelize :: String -> Maybe String
const uncamelize = safeLift(isString, compose(option(""),map(compose(join(" "), map(upperFirst))),match(/(((^[a-z]|[A-Z])[a-z]*)|[0-9]+)/g),
))uncamelize("rockTheCamel")
//=> Just "Rock The Camel"uncamelize({})
//=> Nothing
We’ve created a helper function match
that uses safeAfter
to iron out String.prototype.match
’s behavior of returning an undefined
in case there are no matches. The isArray
predicate ensures that we receive a Nothing
if there are no matches found, and a Just [String]
in case of matches. safeAfter
is great for executing existing or third-party functions in a reliable safe manner.
我们创建了一个辅助函数match
,该函数使用safeAfter
消除String.prototype.match
的行为,即在没有匹配项的情况下返回undefined
的行为。 isArray
谓词可确保在没有找到匹配项的情况下接收Nothing
,在匹配项的情况下接收Just [String]
。 safeAfter
非常适合以可靠的安全方式执行现有功能或第三方功能。
(Tip: safeAfter
works really well with ramda
functions that return a | undefined
.)
(提示: safeAfter
与返回a | undefined
ramda
函数配合使用非常好。)
Our 前言 前面讲了IO多路复用的API,select和poll的缺点是性能不够,客户端连接越多性能下降越明显,epoll的出现解决了这个问题,引用The Linux Programming Interfa ... 风变编程第18关 编程思维 Imagine you have a bag of coins where each coin is of value 5 dollars and you have to ... 工厂方法模式是简单工厂模式的升级版,简单工厂模式不符合设计模式的原则(即:单一职责,开闭原则) 优点: 职责明确,扩展方便 缺点:需要创建多个工厂 实现步骤: 1.将工厂通用方法抽取接口 (例如:IF ... 当今如果说到创业,永远绕不开一个话题:"模式". 非创业者往往最关注的是"产品"或"服务": 初级创业者往往最关注的的是"行业&q ... 工程模式和抽象工厂模式 您是否需要一种非常快速的方法来制作Factory对象? 然后,您需要lambda或其他函数传递! 它不仅快速,而且非常简单. 我敢打赌,如果您对Lambdas相当满意,那么您只 ... 原文链接: 责任链模式 | 菜鸟教程www.runoob.com 顾名思义,责任链模式(Chain of Responsibility Pattern)为请求创建了一个接收者对象的链.这种模式给予请 ... 手机飞行模式功能一直被大家吐槽为最没有用的手机功能,随着智能手机的快速发展,手机很多功能都已经逐渐消失被替代,唯独飞行模式依旧占据着手机设置里的主要地位. 那么问题来了,手机飞行模式到底有什么用? 1 ... 理解 首先委派模式不属于23种设计模式. 所谓委派,个人理解是:将为达到最终结果的事情交给其他人或中间人来干,我只要最终结果,其他的事情,由我委派的人来安排. 更直白的表达就是,比如,我们想要盖一栋楼 ... 积木编程是一款专业的编程学习软件,平台为用户提供多种编程模板使用,还收纳了丰富的编程知识方便用户随时在线学习,更快掌握编程相关技能和知识,专业题库.优质课程.模拟实战都能帮助用户快速提升编程水平. 积 ... 积木编程软件是可以在线可以学习编程的软件,平台给用户提供了大量的编程学习教程,软件还支持在线编程,学习内容丰富,让用户学习起来不会枯燥乏味,就算你是零基础的小白,也可以体验到编程的乐趣. 积木编程官方 ...uncamelize
函数式编程 模式_函数式编程模式:食谱相关推荐
最新文章
热门文章