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. KNN in c++

    Pseudo Code of KNN We can implement a KNN model by following the below steps: Load the data Initiali ...

  2. BZOJ 4800 折半暴搜

    思路: 把它拆成两半  分别搜一发 两部分分别排好序 用two-pointers扫一遍 就可以了. (读入也要用long long) //By SiriusRen #include <cstdi ...

  3. BZOJ 2431 逆序对数列 DP

    2431: [HAOI2009]逆序对数列 Time Limit: 5 Sec Memory Limit: 128 MB Description 对于一个数列{ai},如果有i< j且ai> ...

  4. C - Stones on the Table

    Problem description There are n stones on the table in a row, each of them can be red, green or blue ...

  5. Java 介绍比较全面的一遍文章

    Java简介 Java是由Sun Microsystems公司于1995年5月推出的Java程序设计语言(以下简称Java语言)和Java平台的总称.用Java实现的HotJava浏览器(支持Java ...

  6. 生成器模式(Builder)C++实现

    意图:将一个复杂对象的创建与它的表示分离,使得同样的构建过程可以创建不同的表示. 适用性:1.当创建复杂对象的算法应该独立于该对象的组成部分以及它们的装配方式时. 2.当构建过程必须允许被构建的对象有 ...

  7. html5与css3入门知识点精炼

    <meta name = "keywords" content="…………"/>(网页搜索时要输入的关键字) <meta name = &qu ...

  8. Android高亮TextView

    HighlightTextView Android文本高亮控件,基于View实现. 特点 文本高亮 单词自动换行 高亮词组保持在同一行显示 截图 Demo Java: public class Mai ...

  9. Android开发笔记(11)——DialogFragment & 点击监听

    转载请注明:http://www.cnblogs.com/igoslly/p/6931519.html DialogFragment使用 & 点击监听 /* DialogFragment是用于 ...

  10. 【SQL】数值型函数

    1. CEIL 语法:CEIL(n) 作用:取大于等于数值n的最小整数 SQL> select ceil(9.1),ceil(9.9),ceil(9) from dual; CEIL(9.1)  ...