问题
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