首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >什么是fp-ts谓词?

什么是fp-ts谓词?
EN

Stack Overflow用户
提问于 2021-05-11 13:39:19
回答 1查看 420关注 0票数 1

我正在尝试使用fp-ts实现一些简单的数据验证,并遇到了这个codesandboxexample

代码语言:javascript
复制
import * as E from "fp-ts/lib/Either";
import { getSemigroup, NonEmptyArray } from "fp-ts/lib/NonEmptyArray";
import { sequence } from "fp-ts/lib/Array";
import { pipe } from "fp-ts/lib/pipeable";
import { Predicate } from "fp-ts/lib/function";

type ValidationError = NonEmptyArray<string>;

type ValidationResult = E.Either<ValidationError, unknown>;

type ValidationsResult<T> = E.Either<ValidationError, T>;

interface Validator {
  (x: unknown): ValidationResult;
}

interface Name extends String {}

const applicativeV = E.getValidation(getSemigroup<string>());

const validateName: (
  validations: Array<Validator>,
  value: unknown
) => ValidationsResult<Name> = (validations, value) =>
  validations.length
    ? pipe(
        sequence(applicativeV)(validations.map((afb) => afb(value))),
        E.map(() => value as Name)
      )
    : E.right(value as Name);

const stringLengthPredicate: Predicate<unknown> = (v) =>
  typeof v === "string" && v.length > 4;

const lengthAtLeastFour: Validator = E.fromPredicate(
  stringLengthPredicate,
  () => ["value must be a string of at least 5 characters"]
);

const requiredLetterPredicate: Predicate<unknown> = (v) =>
  typeof v === "string" && v.includes("t");

const hasLetterT: Validator = E.fromPredicate(requiredLetterPredicate, () => [
  'value must be a string that includes the letter "t"'
]);

const validations = [hasLetterT, lengthAtLeastFour];

console.log(validateName(validations, "sim"));
// {left: ['value must be a string that includes the letter "t"', 'value must be a string of at least 4 characters']}

console.log(validateName(validations, "timmy"));
// {right: 'timmy'}

什么是Predicate?在此示例中,它的使用效果如何?我在文档中没有看到任何关于它的用途的解释,只是说它是part of the API,并且它似乎修改了提供的接口。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-05-23 13:16:03

Predicate<A> = (a:A) => boolean

谓词是一个接受参数并返回布尔值的函数。它是filterfromPredicate采用的类型,属于许多类型,比如Option和Option。

例如,

代码语言:javascript
复制
import { filter } from 'fp-ts/Array'
import { pipe } from 'fp-ts/function'
import { fromPredicate } from 'fp-ts/Either'

const errorIfNotThree = fromPredicate<number>(x => x===3, () => 'not three!')
const f = pipe([1,2,3], filter(x => x===3))

errorIfNotThree(3) // right(3)
errorIfNotThree(5) // left('not three!')
f // [3]

在上面的代码中,x => x===3的类型是Predicate<number>,因为它是一个接受数字并返回布尔值的函数

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67481116

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档