相关疑难解决方法(0)

Haskell:Where vs. Let

我是Haskell的新手,我对Where vs. Let感到非常困惑.它们似乎都提供了类似的目的.我已经阅读了WhereLet之间的一些比较,但我无法辨别何时使用每个.有人可以提供一些上下文或者一些示例,说明何时使用其中一个?

哪里与让

where子句只能在一个函数定义的电平来定义.通常,这与let定义的范围相同.唯一的区别是使用警卫时.该where条款的范围扩展到所有警卫.相反,let表达式的范围只是当前的函数子句和guard,如果有的话.

哈斯克尔作弊表

哈斯克尔维基是非常详细,并提供各种案件,但它使用的假设的例子.我觉得它的解释对初学者来说太简短了.

让我们的优势:

f :: State s a
f = State $ \x -> y
   where y = ... x ...
Run Code Online (Sandbox Code Playgroud)

Control.Monad.State

将无法工作,因为where指的是模式匹配f =,其中没有x在范围内.相比之下,如果你开始使用let,那么你就不会遇到麻烦了.

关于Let的优点的Haskell Wiki

f :: State s a
f = State $ \x ->
   let y = ... x ...
   in  y
Run Code Online (Sandbox Code Playgroud)

其中的优点:

f x
  | cond1 x   = a
  | cond2 …
Run Code Online (Sandbox Code Playgroud)

haskell where keyword let

109
推荐指数
5
解决办法
4万
查看次数

Haskell:where子句引用lambda中的绑定变量

我试图使用梯形规则在Haskell中数字地集成一个函数,返回一个反导数,它带有参数a,b,用于集成区间的端点.

integrate :: (Float -> Float) -> (Float -> Float -> Float)

integrate f
  = \ a b -> d * sum [ f (a + d*k) | k <- [0..n] ] - d/2.0 * (f a + f b)
    where
      d = (b - a) / n
      n = 1000
Run Code Online (Sandbox Code Playgroud)

在上面,我用

n - for the number of subintervals
d - for the width of each subinterval
Run Code Online (Sandbox Code Playgroud)

除了lambda中绑定的参数a,b之外,这几乎可以正常工作.我收到错误消息:

Not in scope: `b'
Not in scope: `a'
Run Code Online (Sandbox Code Playgroud)

我可以理解a,b的范围仅限于lambda表达式,但是在Haskell中有一个解决方法,所以我不必在上面的每次出现时写(ba)/ n吗?

lambda haskell where-clause

13
推荐指数
2
解决办法
3699
查看次数

标签 统计

haskell ×2

keyword ×1

lambda ×1

let ×1

where ×1

where-clause ×1