【问题标题】:Haskell: Bound variables within where clauseHaskell:where子句中的绑定变量
【发布时间】:2012-04-16 01:51:15
【问题描述】:

绑定变量的范围是什么?为什么我不能从 where 子句中访问它? 例如,在这个例子中:

someFunc x y = do
  let a = x + 10
  b <- someAction y
  return subFunc
  where
    subFunc = (a * 2) + (b * 3)

这里,subFunc 可以看到 a 而不是 b。 为什么我不能在 where 子句中使用绑定变量?谢谢。

【问题讨论】:

    标签: haskell


    【解决方案1】:

    因为它可能导致不一致。想象一下这段代码:

    printName = do
      print fullName
      firstName <- getLine
      lastName <- getLine
      return ()
      where
        fullName = firstName ++ " " + lastName
    

    此代码不起作用,并且由于这些情况,绑定变量的使用仅限于实际绑定之后的do 块的一部分。对上述代码进行脱糖处理时,这一点变得清晰:

    printName =
      print fullName >>
      getLine >>= (\ firstName ->
        getLine >>= (\ lastName ->
          return ()
        )
      )
      where
        fullName = firstName ++ " " ++ lastName
    

    在这里,可以看到变量firstNamelastName 不在where 子句的范围内,并且它们不能在该子句的任何定义中使用。

    【讨论】:

      猜你喜欢
      • 2012-02-17
      • 1970-01-01
      • 2012-11-17
      • 2011-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-03
      • 2014-03-09
      相关资源
      最近更新 更多