scala – 部分功能应用程序可以懒惰,因为它不会重新计算相同的部
发布时间:2020-12-16 21:34:22 所属栏目:安全 来源:网络整理
导读:为什么部分评估在部分应用的时刻没有严格评估,为什么重新评估不止一次? 作为一个时髦的问题,Scala和Haskell中的例子(有一段时间我认为Haskell的行为会有所不同): 在斯卡拉: scala def f(x: Int)(y: Int) = {println("inside"); x * y}f: (x: Int)(y: Int)
为什么部分评估在部分应用的时刻没有严格评估,为什么重新评估不止一次?
作为一个时髦的问题,Scala和Haskell中的例子(有一段时间我认为Haskell的行为会有所不同): 在斯卡拉: scala> def f(x: Int)(y: Int) = {println("inside"); x * y} f: (x: Int)(y: Int)Int scala> val f2 = f(2) _ f2: Int => Int = <function1> scala> f2(3) inside //internals of f calculated for the first time res7: Int = 6 scala> f2(7) inside //internals of f recalculated res8: Int = 14 在哈斯克尔 Prelude> import Debug.Trace Prelude Debug.Trace> let f x y = trace "inside" x * y Prelude Debug.Trace> let f2 = f 2 Prelude Debug.Trace> f2 3 inside //internals of f calculated for the first time 6 Prelude Debug.Trace> f2 3 inside //internals of f recalculated 6 Prelude Debug.Trace> f2 7 inside //internals of f recalculated 14 我知道有可能重新定义f来返回像下面的代码中的函数,但是有一些功能即使在被完全评估之前也被部分评估: scala> def f(x: Int) = {println("inside"); (y:Int) => x * y} f: (x: Int)Int => Int scala> val f2 = f(2) inside //internals of f calculated only this time f2: Int => Int = <function1> scala> f2(3) res12: Int = 6 scala> f2(7) res13: Int = 14 解决方法
在哈斯克尔,是的.你必须要注意的是你的函数定义是什么样的lambda表达式.例如
Prelude> import Debug.Trace Prelude Debug.Trace> let f x = let x1 = trace "inside" x in y -> x1 * y Prelude Debug.Trace> let f2 = f 2 Prelude Debug.Trace> f2 3 inside 6 Prelude Debug.Trace> f2 3 6 Prelude Debug.Trace> f2 7 14 Sassa NF提出的另一个例子.注意,在g中,跟踪“内部”succ关闭被重新创建每个调用,而在h中,闭包被绑定到h一次.减少Eta并不保留Haskell中的操作语义! Prelude Debug.Trace> let g = x -> (trace "inside" succ) x :: Int Prelude Debug.Trace> g 1 inside 2 Prelude Debug.Trace> g 2 inside 3 Prelude Debug.Trace> g 3 inside 4 Prelude Debug.Trace> let h = trace "inside" succ :: Int -> Int Prelude Debug.Trace> h 1 inside 2 Prelude Debug.Trace> h 2 3 Prelude Debug.Trace> h 3 4 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |