用于状态转换的flatMap()的实现 [英] Implementation of flatMap() for State transition

查看:108
本文介绍了用于状态转换的flatMap()的实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

练习6.8,Chiusano和Bjarnason,Scala中的函数式编程,p。 87询问如何为下列特征实现flatMap():

  trait RNG {
def nextInt:(Int ,RNG)
}

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

答案键给出了以下解决方案:

  def flatMap [A​​,B](f:Rand [A])(g:A => Rand [B]):Rand [B] = 
rng => {
val(a,r1)= f(rng)
g(a)(r1)//我们沿着
}传递新的状态

Stackoverflow为flatMap()/ monad问题提供了很多答案,但没有一个能够回答我关于最后一行代码的问题。



我不明白该行的语法

  g(a)( r1)

(1)我不明白g(a)(r1)是如何评估的。 (r1)提供了什么句法功能?因为g只有一个参数:A.
(2)如果g(a)已经返回类型Rand [B],那么为什么行不结束这里?
(3)由g(a)返回的Rand [B]和第二组括号之间的关系是什么?(r1)?
(4)如果flatMap()的这个实现的返回类型是Rand [B],它等于RNG =>(A,RNG),箭头右边的括号括起来如何生成?如果我不得不猜测,我会说他们是由评估生成的,(r1),但我不太了解这个代码给出我的问题1至3.

解决方案

请记住,我们在一个新的匿名函数中调用 f g 如线所示

  rng => {...} 

g 返回a Rand [B] 当给出 A ,所以 g(a)的计算结果为从 RNG (A,RNG)的函数。

因此 g(a)会返回一个函数,期望 RNG 作为它的参数,我们可以用 r1 来调用它,它的类型是 RNG



调用的结果是(B,RNG)。现在,由于 flatMap 签名期望您返回与 Rand [B] > RNG => (B,RNG),我们在函数中返回(B,RNG),它完全符合签名。

Exercise 6.8, Chiusano and Bjarnason, Functional Programming in Scala, p. 87 asks how one might implement flatMap() for the following trait:

trait RNG {
  def nextInt: (Int, RNG)
}

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

The answer key gives the following solution:

def flatMap[A,B](f: Rand[A])(g: A => Rand[B]): Rand[B] =
rng => {
  val (a, r1) = f(rng)
  g(a)(r1) // We pass the new state along
}

Stackoverflow provides many answers to flatMap()/monad questions, but none which for me answered my questions regarding the next to last line of code.

I do not understand the syntax of the line

g(a)(r1)

(1) I do not understand how g(a)(r1) evaluates. What syntactic function is served by (r1)? The line does not exemplify currying, I do not believe, since g takes only one argument: A. (2) If g(a) will already return the type Rand[B], then why does not the line end here? (3) what is the relation between the Rand[B] returned by g(a) and the second set of parentheses: (r1)? (4) if the return type of this implementation of flatMap() is Rand[B], which is equal to RNG => (A, RNG), how are the enclosing parentheses to the right of the arrow generated? If I had to guess I would say they are generated by the evaluation, (r1), but I do not really understand this code given my questions 1 through 3.

解决方案

Remember that we're calling f and g inside a new anonymous function, as indicated by the line

rng => { ... }

g returns a Rand[B] when given an A, so g(a) evaluates to a function from RNG to (A, RNG).

So g(a) returns a function expecting an RNG as its argument, we can then call this with our r1, which is of type RNG.

The result of the call is (B, RNG). Now since the flatMap signature expects you to return a Rand[B] which is the same as RNG => (B, RNG) and we return (B, RNG) inside our function, it exactly matches the signature.

这篇关于用于状态转换的flatMap()的实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆