Skip to content

Commit 63ad862

Browse files
committed
add Haskell snippet for Either monad to handle errors in computations
1 parent 2c31172 commit 63ad862

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
---
2+
title: Either Monad for Error Handling
3+
description: Using the Either monad to handle errors in a computation.
4+
author: ACR1209
5+
tags: haskell, monads, either, error handling
6+
---
7+
8+
```hs
9+
safeDiv :: Int -> Int -> Either String Int
10+
safeDiv _ 0 = Left "Division by zero error"
11+
safeDiv x y = Right (x `div` y)
12+
13+
main :: IO ()
14+
main = do
15+
let result = do
16+
a <- safeDiv 10 2
17+
b <- safeDiv a 0 -- This will trigger an error
18+
return b
19+
print result -- Output: Left "Division by zero error"
20+
```

0 commit comments

Comments
 (0)