При воспроизведении данного куска кода:
half x = if even x
then Just (x `div` 2)
else Nothing
printMaybe m = case m of
Nothing -> putStrLn "List was empty!"
Just x -> print x
main = do
let halfN = Just 4 >>= half
halfN >>= printMaybe
Возникает ошибка:
main.hs:9:1: error:
* Couldn't match expected type `IO t0' with actual type `Maybe ()'
* In the expression: main
When checking the type of the IO action `main'
|
9 | main = do
| ^
main.hs:11:13: error:
* Couldn't match type `IO' with `Maybe'
Expected type: Maybe a0 -> Maybe ()
Actual type: Maybe a0 -> IO ()
* In the second argument of `(>>=)', namely `printMaybe'
In a stmt of a 'do' block: halfN >>= printMaybe
In the expression:
do let halfN = Just 4 >>= half
halfN >>= printMaybe
|
11 | halfN >>= printMaybe
Вот способ решения этой проблемы:
half x = if even x
then Just (x `div` 2)
else Nothing
printMaybe m = case m of
Nothing -> putStrLn "List was empty!"
Just x -> print x
main = do
let halfN = Just 4 >>= half
printMaybe $ halfN
Не могу понять, почему изначальная программа не работает. Сначала получаем половину числа в функции half
(в виде монады Maybe
), после чего "пропихиваем" это значение в функцию вывода - printMaybe
.
Почему первоначальная версия кода не работает?