函数式编程 模式

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类型的其他示例包括MaybeEitherAsync等。 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提供safesafeAftersafeLift功能,使我们能够使用更多的可预见的执行代码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 uncamelize

函数式编程 模式_函数式编程模式:食谱相关推荐

  1. epoll哪些触发模式_网络编程:epoll

    前言 前面讲了IO多路复用的API,select和poll的缺点是性能不够,客户端连接越多性能下降越明显,epoll的出现解决了这个问题,引用The Linux Programming Interfa ...

  2. 风变编程第18关 编程思维_动态编程变得容易

    风变编程第18关 编程思维 Imagine you have a bag of coins where each coin is of value 5 dollars and you have to ...

  3. 工厂方法模式_工厂方法模式

    工厂方法模式是简单工厂模式的升级版,简单工厂模式不符合设计模式的原则(即:单一职责,开闭原则) 优点: 职责明确,扩展方便 缺点:需要创建多个工厂 实现步骤: 1.将工厂通用方法抽取接口 (例如:IF ...

  4. python的盈利模式_八大盈利模式是什么?一篇文教会你盈利模式分析!

    当今如果说到创业,永远绕不开一个话题:"模式". 非创业者往往最关注的是"产品"或"服务": 初级创业者往往最关注的的是"行业&q ...

  5. 工程模式和抽象工厂模式_功能工厂模式

    工程模式和抽象工厂模式 您是否需要一种非常快速的方法来制作Factory对象? 然后,您需要lambda或其他函数传递! 它不仅快速,而且非常简单. 我敢打赌,如果您对Lambdas相当满意,那么您只 ...

  6. 哈斯机床进去debug模式_责任链模式

    原文链接: 责任链模式 | 菜鸟教程​www.runoob.com 顾名思义,责任链模式(Chain of Responsibility Pattern)为请求创建了一个接收者对象的链.这种模式给予请 ...

  7. shell开启飞行模式_手机飞行模式有什么用 手机飞行模式介绍【详解】

    手机飞行模式功能一直被大家吐槽为最没有用的手机功能,随着智能手机的快速发展,手机很多功能都已经逐渐消失被替代,唯独飞行模式依旧占据着手机设置里的主要地位. 那么问题来了,手机飞行模式到底有什么用? 1 ...

  8. 代理模式 委派模式 策略模式_设计模式 - 委派模式

    理解 首先委派模式不属于23种设计模式. 所谓委派,个人理解是:将为达到最终结果的事情交给其他人或中间人来干,我只要最终结果,其他的事情,由我委派的人来安排. 更直白的表达就是,比如,我们想要盖一栋楼 ...

  9. python积木编程软件_积木编程下载-积木编程app下载v1.0.0-西西软件下载

    积木编程是一款专业的编程学习软件,平台为用户提供多种编程模板使用,还收纳了丰富的编程知识方便用户随时在线学习,更快掌握编程相关技能和知识,专业题库.优质课程.模拟实战都能帮助用户快速提升编程水平. 积 ...

  10. python积木编程软件_积木编程软件手机版下载

    积木编程软件是可以在线可以学习编程的软件,平台给用户提供了大量的编程学习教程,软件还支持在线编程,学习内容丰富,让用户学习起来不会枯燥乏味,就算你是零基础的小白,也可以体验到编程的乐趣. 积木编程官方 ...

最新文章

  1. 描述一下Spring框架的作用和优点?
  2. 成功解决SQL server服务,远程过程调用失败
  3. 成功解决NameError: name 'apply' is not defined
  4. python中dict的fromkeys用法教程
  5. SAP Cloud Application Programming CatalogService 默认的路径
  6. openstack horizon国际化分析
  7. Python+Selenium练习篇之2-利用ID定位元素
  8. vue 前端设置允许跨域_[web]记一次sanic+vue跨域问题
  9. WordPress Plupload插件未明跨站脚本漏洞
  10. 深度学习之于传统计算机视觉
  11. 11.20,winfrom,增加,查询,删除,修改
  12. 赢在AI,人工智能技术体验
  13. php 检查txt中全角大写字母的个数
  14. python在线运行编程工具模板源码[网页版]
  15. 【异常处理】Word2016 出现“此功能看似已中断 并需要修复
  16. 第六章 算法algorithms
  17. 将坐标系统保存为一个文件.prj
  18. 【scratch音乐课】天空之城:音符与节拍、消息与链表
  19. RSA组件之掩码生成函数(MGF)的实现(C源码)
  20. python 树莓派实验一:跑马灯

热门文章

  1. 【Linux】Ubuntu下C语言访问MySQL数据库入门
  2. 多存多取问题 java
  3. django 别名与命名空间 reverse反转得到路径
  4. python-字符串的格式化输出format
  5. python Django ORM ,用filter方法表示“不等于”的方法
  6. 只要加一行,让 IE 五倍速执行 JavaScript
  7. 洗礼灵魂,修炼python(8)--高效的字典
  8. 一张图看完成都云栖大会的精彩,请用心感受!
  9. MySQL学习笔记之MySQL安装详解
  10. 程序员应具备的职业素质