如何使用EXCEPTION效果从PureScript函数返回值?

Alb*_*rly 2 exception-handling effects purescript

我刚刚开始学习PureScript效果,并且我试图制作一个具有EXCEPTION效果的函数.

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"
Run Code Online (Sandbox Code Playgroud)

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

无法匹配类型

    String

  with type

    Eff
      ( err :: EXCEPTION
      | eff0
      )
      String
Run Code Online (Sandbox Code Playgroud)

我知道lengthGt5需要在非异常的情况下返回一个包装在Eff中的String,但是我不知道如何在值周围创建一个"空效果包装器" a.我在考虑这个吗?

Alb*_*rly 7

我想出了我所缺少的东西.要在非例外情​​况下返回值,您必须调用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)
Run Code Online (Sandbox Code Playgroud)

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

class (Apply f) <= Applicative f where
    pure :: forall a. a -> f a
Run Code Online (Sandbox Code Playgroud)

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

因此pure获取值a,并返回包含在类型构造函数中的值 - 在这种情况下类型构造函数是Eff e