首页 > 解决方案 > 带警卫的功能:使用“where”时出现语法错误

问题描述

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,它就会给出语法错误:

错误:输入“|”时解析错误</p>

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

标签: haskellsyntax

解决方案


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

推荐阅读