如何从具有EXCEPTION效果的PureScript函数返回值? [英] How do I return a value from a PureScript function with an EXCEPTION effect?

查看:139
本文介绍了如何从具有EXCEPTION效果的PureScript函数返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始了解PureScript效果,而我试图使一个具有EXCEPTION效果的功能。

I've just started learning about PureScript effects, and I'm stuck trying to make a function that has an EXCEPTION effect.

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"

当我尝试运行这个我收到以下错误

When I try and run this I get the following error

无法匹配类型

    String

  with type

    Eff
      ( err :: EXCEPTION
      | eff0
      )
      String

我知道lengthGt5需要返回一个包含在Eff中的String,例外情况,但我不知道如何在值 a 之间创建一个空效果包装器。我在想这个权利吗?

I understand that lengthGt5 needs to return a String wrapped in an Eff in the non-exception case, but I'm not sure how I can create an "empty effect wrapper" around the value a. Am I thinking about this right?

推荐答案

我想到了我失踪了什么。要返回非异常情况下的值,您必须调用纯一个

I figured out what I was missing. To return the value in the non-exception case, you have to call 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 在应用类型类中定义,定义如下:

pure is defined in the Applicative type class defined as follows:

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




Applicative是Apply的一个子类,定义了纯函数。纯
获取一个值,并返回一个值,该类型已被
类型构造函数f包裹。

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

So pure takes the value a, and returns that value wrapped in a type constructor - in this situation the type constructor is Eff e

这篇关于如何从具有EXCEPTION效果的PureScript函数返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆