3

我刚刚开始学习 PureScript 效果,我一直在尝试制作一个具有异常效果的函数。

lengthGt5 :: forall eff. String -> Eff (err :: EXCEPTION | eff) String
lengthGt5 a = if (length a <= 5)
              then throwException $ error "Word is not the right length!"
              else a

main = do
  word <- catchException handleShortWord (lengthGt5 "test")
  log word

  where
    handleShortWord err = do
      log (message err)
      return "Defaut::casserole"

当我尝试运行它时,我收到以下错误

无法匹配类型

    String

  with type

    Eff
      ( err :: EXCEPTION
      | eff0
      )
      String

我知道 lengthGt5 在非异常情况下需要返回一个包裹在 Eff 中的 String ,但我不确定如何在 value 周围创建一个“空效果包装器” a。我在想这个吗?

4

1 回答 1

8

我弄清楚我错过了什么。要在非异常情况下返回值,您必须调用pure a

lengthGt5 :: forall eff. String -> Eff (err :: EXCEPTION | eff) String
lengthGt5 a = if (length a <= 5)
              then throwException $ error "Word is not the right length!"
              else (pure a)

pure在Applicative类型类中定义如下:

class (Apply f) <= Applicative f where
    pure :: forall a. a -> f a

Applicative 是 Apply 的子类,定义了纯函数。pure 接受一个值并返回一个其类型已用类型构造函数 f 包装的值。

所以pure取值a,并返回包装在类型构造函数中的值——在这种情况下,类型构造函数是Eff e

于 2016-05-22T17:47:29.363 回答