【问题标题】:How do I return a value from a PureScript function with an EXCEPTION effect?如何从具有异常效果的 PureScript 函数返回值?
【发布时间】:2016-05-22 16:28:34
【问题描述】:

我刚刚开始学习 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 创建一个“空效果包装器”。我考虑的对吗?

【问题讨论】:

标签: exception-handling effects purescript


【解决方案1】:

我知道我错过了什么。要在非异常情况下返回值,您必须调用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 的子类,定义了纯函数。纯的 接受一个值并返回一个其类型已用 类型构造函数 f。

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

【讨论】:

    猜你喜欢
    • 2013-06-03
    • 2020-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多