gpt4 book ai didi

scala - 在 Scala 中进行柯里化(Currying),使这些语句编译的类型是什么?

转载 作者:行者123 更新时间:2023-12-04 14:38:49 26 4
gpt4 key购买 nike

所以我在Scala中有这个功能:

def f(a: Int)(b: Int)(c: Double)(d: Double): Double = a * c + b * d

问题是使以下语句编译的三种类型是什么。
def g: <Type1> = f(1)(2)(3.0) 
def h: <Type2> = f(1)(2)
def k: <Type3> = f(1)

我对 Scala 还是很陌生,我并不真正理解柯里化(Currying)的概念。也许通过一些解释来回答这个问题真的会对我有所帮助。谢谢。

最佳答案

首先,一件主要的事情:接受两个参数的函数ab并返回一个值 c可以看作是一个接受 a 的函数。并返回一个接受 b 的函数并返回 c .这种“观点的改变”被称为柯里化(Currying)。

想象一个对两个数字求和的函数。你给它 2 和 3,它返回 5。它可以看作是一个函数,它接受一个数字,并返回一个从一个数字到一个数字的函数。你给它一个 2,它返回一个函数,该函数接受一些数字并将 2 添加到它。

现在,您要求的一些类型:

// pseudocode!

def g: Double => Double
= f(1)(2)(3.0) // we supply three params and are left with only one, "d"
= (d: Double) => 1 * 3.0 + 2 * d // we comply with g's type

def h: Double => Double => Double // or (Double, Double) => Double
= f(1)(2) // we supply two params and are left with two more, "c" and "d"
= (c: Double)(d: Double) => 1 * c + 2 * d // we comply with h's type

def k: Double => Double => Double => Double // or (Double, Double, Double) => Double
= f(1) // we supply one param and are left with three more, "b", "c" and "d"
= (b: Double)(c: Double)(d: Double) => 1 * c + b * d // we comply with k's type

关于scala - 在 Scala 中进行柯里化(Currying),使这些语句编译的类型是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49114652/

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