Hello everyone, I am learning purescript.
I have encapsulated some functions, such as a function to read a file, its signature may be like this:
myReadFile :: String -> Effect String
But this may go wrong, Although there is a try
function to catch any errors that occur, and get a Either
.
But I want to return different error prompts under different circumstances, so I changed it to this:
myReadFile :: String -> Effect (Either String String)
It looks good now, when there is an error reading the file, I will get a Left String
, This is an error message, And when there is no error I will get a Right String
, This is the content of the file I need.
The only problem is that this type has a lot of inconvenience to deal with, For example, if I have a function:
myFun :: String -> String -> String
Now, I need to input the content of the file and the string “abc” into this function, In a do
region, I would write like this:
do
e_str <- myReadFile "./aaa.txt"
e_s <- lift2 myFun e_str (pure "abc")
...
In complex situations, I would also use sequence
join
and other functions to adjust the type.
Why not encapsulate “Effect” and “Either” into a new type? After all, most operations with side effects may go wrong.
E.g:
data EEffect a = EEffect (Effect (Either String a))
toNatural :: forall a. EEffect a -> Effect (Either String a)
toNatural (EEffect a) = a
instance functorEEffect :: Functor EEffect where
map :: forall a b. (a -> b) -> EEffect a -> EEffect b
map f v =
EEffect
$ do
vv <- toNatural v
pure $ map f vv
my question:
- Is this idea correct?
- If feasible, is there a similar type, but I did not see it?