gpt4 book ai didi

scala - 什么是 Scala 或函数式编程中的组合子

转载 作者:行者123 更新时间:2023-12-04 14:45:41 25 4
gpt4 key购买 nike

我正在学习 Scala 和 FP,在书中 "Functional Programming in Scala " 术语 组合器在“Functional Design and Combinator Libraries”一章中提到的 Combinators 定义为:

Looking back at our implementations, we’ll notice a common pattern: each of our functions has a type of the form RNG => (A, RNG) for some type A. Functions of this type are called state actions or state transitions because they transform RNG states from one to the next. These state actions can be combined using combinators, which are higher-order functions that we’ll define in this section. Since it’s pretty tedious and repetitive to pass the state a long ourselves, we want our combinators to pass the state from one action to the next automatically.



那么组合子是一种高阶函数还是一种高阶函数,或者它们是某种技术(设计模式)还是某种代数类型?

为了使回答更准确,这些问题是:
什么是组合子,它们来自哪里,它们在哪里使用,它们有什么特别之处?

最佳答案

组合器实际上是一个更一般的概念。组合器,顾名思义,就是将其他事物组合在一起的东西。 (就像终结者是终止其他事物的事物一样。)

Combinator 的思想是它组合的东西和被组合的东西具有相同的类型,这样你就可以在 Combinator 的结果上再次调用 Combinator。

Combinator 出现的流行领域之一是解析,使用所谓的 Parser Combinator 库。这个想法是,通过使用 Combinator 构建更简单的解析器的组合,您可以从更简单的解析器中构建更复杂的解析器。

例如,Parser Combinator 库可能只提供一个简单的解析器:一个只能解析一个字符的解析器。如果你想解析任何更复杂的东西,库提供了几个组合器:

  • 序列组合器采用两个解析器并生成一个解析器,该解析器识别第一个解析器识别的字符串,然后是第二个解析器识别的字符串。
  • 交替组合器采用两个解析器并生成一个解析器,该解析器识别第一个解析器识别的字符串或第二个解析器识别的字符串。
  • 重复组合器采用一个解析器并生成一个解析器,该解析器识别输入解析器识别的字符串的零次或多次重复。

  • 使用这三个 Combinator 和基本的“单字符”解析器,您可以解析所有常规语言。

    这里重要的是 Combinator 返回一个新的解析器。它不执行解析器。

    在函数式语言中,解析器和组合器通常都是函数,因此组合器将是高阶函数。但是,也不必如此。例如。解析器可以是对象和组合器函数,这使得组合器只是普通函数。

    所以,使用 Combinators,你总是有两件事:
  • 一组特定“种类”的“原语”
  • 一组组合器,它们采用该特定“种类”的一个或多个值并返回相同特定“种类”的值
  • 关于scala - 什么是 Scala 或函数式编程中的组合子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58681172/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com