Once we’re using Maybes throughout our code, it stands to reason that at some point we’ll get a Maybe and want to continue applying transformations. We might get a Nothing and want to perform those same transformations on some default value. In this lesson, we’ll do exactly that! We’ll see how we can use the alt method on the Maybe to recover from a Nothing and continue applying transformations with a Just.

The use case is that you get a Nothing from previous transformation, but you wish not to stop with Nothing, you want oto provide a default Maybe value and continue the process.

const crocks = require('crocks')
const { and, compose, isEmpty, isString, Maybe, not, prop, safe } = crocks
const { join, split, toLower } = require('ramda') const article = {
id: ,
name: 'Learning crocksjs functional programming library'
}; const createUrlSlug = compose(join('-'), split(' '), toLower);
const createUrl = slug => `https://egghead.io/articles/${slug}`;
const createUrlFromName = compose(createUrl, createUrlSlug);
const isNonEmptyString = and(not(isEmpty), isString); const getArticleName = obj => prop('name', obj)
.chain(safe(isNonEmptyString)) // If previous return Just(""), we want to continue check make sure it is not empty, other return Nothing
.alt(Maybe.of('page not found')); // If return Nothing then use alt value const getArticleUrl = obj => getArticleName(obj)
.map(createUrlFromName)
.option('default'); const url = getArticleUrl(article); console.log(url)

We are also able to chain multi 'alt' together, it will return first Just():

const bad = Nothing()
const good = Just()
const anotherGood = Just()
console.log(Nothing()
.alt(bad)) // Nothing console.log(Nothing()
.alt(bad)
.alt(good)) // Just 42 console.log(Nothing()
.alt(bad)
.alt(good)
.alt(anotherGood)) // Just 42

More example:

const Maybe = require('crocks/Maybe')
const alt = require('crocks/pointfree/alt')
const converge = require('crocks/combinators/converge')
const prop = require('crocks/Maybe/prop') const {Just} = Maybe; // maybeGetDisplay :: a -> Maybe b
const maybeGetDisplay = prop('display') // maybeGetFirst :: a -> Maybe b
const maybeGetFirst = prop('first') // maybeGetLast :: a -> Maybe b
const maybeGetLast = prop('last') // maybeConcatStrings :: Maybe String -> Maybe String -> Maybe String
const maybeConcatStrings = x => y => Just(x => y => x + ' ' + y).ap(x).ap(y).alt(x).alt(y) // maybeMakeDisplay :: a -> Maybe String
const maybeMakeDisplay = converge(maybeConcatStrings, maybeGetFirst, maybeGetLast) // maybeGetName :: a -> Maybe b
const maybeGetName = converge(alt, maybeGetDisplay, maybeMakeDisplay) console.log(maybeMakeDisplay({ display: 'Jack Sparrow' }))
//=> Just('Jack Sparrow') console.log(maybeMakeDisplay({ first: 'J', last: 'S' }))
//=> Just('J S') console.log(maybeMakeDisplay({ display: 'Jack Sparrow', first: 'J', last: 'S' }))
//=> Just('Jack Sparrow') console.log(maybeMakeDisplay({ first: 'J' }))
//=> Just('J') console.log(maybeGetName({ last: 'S' }))
//=> Just('S')

[Javascript Crocks] Recover from a Nothing with the `alt` method的更多相关文章

  1. [Javascript Crocks] Recover from a Nothing with the `coalesce` Method

    The alt method allows us to recover from a nothing with a default Maybe, but sometimes our recovery ...

  2. [Javascript Crocks] Apply a function in a Maybe context to Maybe inputs (curry & ap & liftA2)

    Functions are first class in JavaScript. This means we can treat a function like any other data. Thi ...

  3. [Javascript Crocks] Make your own functions safer by lifting them into a Maybe context

    You probably have functions that aren’t equipped to accept a Maybe as an argument. And in most cases ...

  4. [Javascript Crocks] Compose Functions for Reusability with the Maybe Type

    We can dot-chain our way to great success with an instance of Maybe, but there are probably cases wh ...

  5. [Javascript Crocks] Flatten Nested Maybes with `chain`

    Sometimes, we run into situations where we end up with a Maybe within the context of another Maybe. ...

  6. [Javascript Crocks] Safely Access Nested Object Properties with `propPath`

    In this lesson, we’ll look at the propPath utility function. We’ll ask for a property multiple level ...

  7. [Javascript Crocks] Safely Access Object Properties with `prop`

    In this lesson, we’ll use a Maybe to safely operate on properties of an object that could be undefin ...

  8. [Javascript Crocks] Create a Maybe with a `safe` Utility Function

    In this lesson, we’ll create a safe function that gives us a flexible way to create Maybes based on ...

  9. [Javascript Crocks] Understand the Maybe Data Type

    In this lesson, we’ll get started with the Maybe type. We’ll look at the underlying Just and Nothing ...

随机推荐

  1. zoj3478

    最短路 吐槽一下...最先开始写了个地图哈希,6kb,然后不是正解,又写了个spfa,4kb,还是不对,无奈抄标程,结果把spfa改成dijiestra就对了... 由于只有两个变量,所以我们设一个四 ...

  2. 第2课 Git配置文件的妙用

    2-1 "git config"  指令的用法 文件夹中".git"子文件夹内的config文件的优先权>登录账号的home directory中的.gi ...

  3. Python入门 五、学着机器思考

    正则表达式(1) import re text = "Hi,I am Shirley Hilton.I am his wife." m = re.findall(r"hi ...

  4. Prime Path(bfs)

    http://poj.org/problem?id=3126 题意:给两个四位数n,m,将n变成m需要多少步,要求每次只能改变n的某一位数,即改变后的数与改变前的数只有一位不同,且每次改变后的数都是素 ...

  5. Redis(二)-Win系统下安装

    下载地址:https://github.com/MSOpenTech/redis/releases. Redis 支持 32 位和 64 位.这个需要根据你系统平台的实际情况选择,这里我们下载 Red ...

  6. ACM_来自不给标题的菜鸟出题组(巴什博弈+素数判定)

    来自不给标题的菜鸟出题组 Time Limit: 2000/1000ms (Java/Others) Problem Description: 大B和小b合作出一道程序设计月赛的题,他们的想法是给定一 ...

  7. WebApi中对请求参数和响应内容进行URL编码解码

    项目经测试,发现从IE提交的数据,汉字会变成乱码,实验了网上很多网友说的给ajax加上contentType:"application/x-www-form-urlencoded; char ...

  8. VM虚拟机中Ubuntu中执行apt-get update失败的解决方法(可能有效)

    首先确保虚拟机是连接网络的,可以用ping命令检测一下看是否连通网络.采用nat网络的时候确保服务是开的. 如果之前执行过apt-get update命令但是失败了,执行一下      rm -rf ...

  9. 在64位WindowsServer2012R2中安装Oracle10g第二版(10.2.0.4.0)-20160106

      1.操作系统版本 用于安装数据库的操作系统镜像文件名为:cn_windows_server_2012_r2_vl_with_update_x64_dvd_6052729.iso 安装DataCen ...

  10. 安卓JNI使用C++类

    安卓JNI使用C++类,同时可使用C++的类成员变量,这就必须保证程序持续保存Native状态,即长期维护C++对象的地址.完成初始化之后,需要使用对象成员的java层函数需要传入对象的地址. 一.N ...