gpt4 book ai didi

java - 什么是组合器以及如何用 java 编写它们

转载 作者:行者123 更新时间:2023-12-01 12:06:05 24 4
gpt4 key购买 nike

我正在看书Fp In Scala作者谈论的是纯粹的功能状态。

例如,作者这样编写纯随机生成器(伪代码):

def newSeed = (this.seed * 0x5DEECE66DL + 0xBL) & 0xFFFFFFFFFFFFL
def obj = new RandomG(newSeed)
def n = newSeed >>> 16
[n,obj]

这里作者返回值(n)状态(obj)。从返回的状态中,我们可以获得给定种子的随机常量

后来作者说:

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.

他定义:

type Rand[+A] = RNG => (A, RNG)

组合器如下所示:

def unit[A](a: A): Rand[A] = rng => (a, rng)

由此我有两个问题:

  1. unit 是如何工作的?我不明白这个主意。
  2. 如何用 Java 编写相同的单元

提前致谢。

最佳答案

unit 只是将普通值 a: A“包装”为 Rand[A] 的一种方式,即函数RNG => (A, RNG),通过让它返回未修改的 RNG 。我不会真正将 unit 称为“组合器”(我保留该术语来表示对函数进行操作的函数,例如 maptraverse,并且你引用的段落似乎同意),但这个词对不同的人来说意味着不同的东西。

不幸的是,在 Java 中,我们没有类型别名或元组,因此我们必须显式定义类型:

public class RngAnd<A> {
public final RNG rng;
public final A a;
public RngAnd(RNG rng, A a) {
this.rng = rng;
this.a = a;
}
}

@FunctionalInterface
public interface Rand<A> {
RngAnd<A> apply(RNG rng);
}

public static <A> Rand<A> unit(A a) {
return rng -> new RngAnd<A>(rng, a);
//I think that syntax is right, I haven't used it. In Java 7 it would be:
return new Rand<A>{
public RngAnd<A> apply(Rng rng) {
return new RngAnd<A>(rng, a);
}
};
}

关于java - 什么是组合器以及如何用 java 编写它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27588588/

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