带警卫的功能:使用“ where”时的语法错误

时间:2019-10-27 22:24:09

标签: haskell syntax

MWE:

import Control.Monad.State.Lazy

fibStep :: State (Integer, Integer) ()
fibStep = state $ \(a, b) -> ((), (b, a + b))

execStateN :: Int -> State s a -> s -> s
execStateN n m s
  | n == 1 = execState m s
  | n > 1 = let s' = execState m s in
              execStateN (n - 1) m s'
  -- | n > 1 = execStateN (n - 1) m s' where s' = execState m s
  | otherwise = error "undefined behaviour"

它可以工作,但是一旦我取消注释where变体并注释let变体,它就会产生语法错误:

  

错误:解析输入“ |”上的错误

我检查了缩进,它们很好。怎么了?

1 个答案:

答案 0 :(得分:6)

where的作用范围是所有守卫,因此您将其放在守卫的末尾,例如:

execStateN :: Int -> State s a -> s -> s
execStateN n m s
  | n == 1 = execState m s
  | n > 1 = execStateN (n - 1) m s'
  | otherwise = error "undefined behaviour"
  where s' = execState m s