假设我有两个功能:
not_force_eval :: IO (Either SomeException [[[Integer]]])
not_force_eval = (try $ evaluate [[[3 + 4, 6 * 2, 5 `div` 0]]])
:: IO (Either SomeException [[[Integer]]])
force_eval :: IO (Either SomeException [[[Integer]]])
force_eval = (try $ evaluate $!! [[[3 + 4, 6 * 2, 5 `div` 0]]])
:: IO (Either SomeException [[[Integer]]])
force_eval
与not_force-eval
几乎相同,只有($!!)
,这就是为什么表达式[[[3 + 4, 6 * 2, 5 `div` 0]]]
被强制评估的原因。
然后我试着找出我的功能是否会引发任何异常。
show_res = do
res <- force_eval
case res of
Left exc -> print $ displayException exc
Right smth -> print smth
运行show_res
我得到:
&#34;除以零&#34;
然后我将force_eval
替换为not_force_eval
show_res = do
res <- not_force_eval
case res of
Left exc -> print $ displayException exc
Right smth -> print smth
正在运行show_res
我明白了:
[[[7,12,***例外:除以零
所以,问题是:有没有办法在抛出异常之前获得已经评估过的结果?例如,我想制作一个字符串:
&#34;除以零; [[[7,12,...&#34;
答案 0 :(得分:3)
您可以使用以下内容:(未经测试)
safePrefix :: String -> IO (String, Maybe SomeException)
safePrefix s = do
r1 <-try (evaluate s)
case r1 of
Left exc -> return ("", Just exc)
Right "" -> return ("", Nothing)
Right (x:xs) -> do
r2 <- try (evaluate x)
case r2 of
Left exc -> return ("", Just exc)
Right x' -> do
(p, exc) <- safePrefix xs
return (x':p, exc)