How do I return a value from a PureScript function with an EXCEPTION effect?

风流意气都作罢 提交于 2019-12-11 01:05:28

问题


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

Could not match type

    String

  with type

    Eff
      ( err :: EXCEPTION
      | eff0
      )
      String

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?


回答1:


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 is defined in the Applicative type class defined as follows:

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.

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



来源:https://stackoverflow.com/questions/37376783/how-do-i-return-a-value-from-a-purescript-function-with-an-exception-effect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!