Haskell exceptions

If I understood correctly, exceptions in Haskell were mainly intended to work in the IO monad. At the very least, an exception could be caught inside the IO monad.

But sometimes even pure functions can throw an exception, for example. read "..." :: Int(when the reading line does not represent an integer), the operator (!!)(when we try to get an item outside the range of the list), etc. And this is true behavior, I do not deny. However, I would not want to change the signature of the function just to be able to catch a possible exception, because in this case I have to change the signature of all the functions in the call stack before.

Is there any template to handle exceptions more convenient in Haskell from the IO monad? Maybe I should use unsafePerformIOin this case? How is it "safe" to use unsafePerformIOonly to detect exceptions in pure functions?

+5
source share
4 answers

In clean code, it is usually best to avoid exceptions that occur first. That is, do not use headif you are not sure that the list is not empty, and use readspattern matching instead readto check for parsing errors.

, , , .. error, , .

, , IO , " ". , Maybe ErrorT, , .

+9

! (, , - )

, ( , , ). , , ; , :

head :: [a] -> Maybe a

eqHead :: (Eq a) => [a] -> Maybe [a]
eqHead xs = do
    h <- head xs
    return $ filter (== h) xs

So eqHead "" ( , ), Maybe -ness head, , head - .

, , Haskell , Java. Haskell . , , , . , , , -, .

, , , .

+5

, , read, , , ?

, spoon.

+3

, , , " ". .

( FP) " [a] -> a, a a." , , - .

head , , , Maybe . , .

+2

All Articles