exception-handling - 如何从具有异常效果的 PureScript 函数返回值?

标签 exception-handling effects purescript

我刚刚开始学习 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 中的字符串,但我不确定如何围绕值 a 创建一个“空效果包装器” .我考虑的对吗?

最佳答案

我知道我错过了什么。要在非异常情况下返回值,您必须调用 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 is a subclass of Apply and defines the pure function. pure takes a value and returns a value whose type has been wrapped with the type constructor f.

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

关于exception-handling - 如何从具有异常效果的 PureScript 函数返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37376783/

相关文章:

C++:使用 segvcatch 安全吗?

python - 手动触发 Django 邮件错误报告

c# - gdi+ 中的 Lomography 效果

javascript - 如何让一个div水平滑入?

python - Pygame粒子效果

javascript - 将 React 组件与 Pux 集成——require() 从何而来?

purescript - 如何映射具有异构元素类型的记录

java中的java.lang.NullPointerexception

c++ - 函数 try catch 语法和 main

javascript - 如何从外部模块生成 Pux 操作?