如何使用streaming库对生成的流值应用函数?(报错求助)
mapM Let's break down the error you're seeing and fix it step by step.
The Root Cause
The error message spells out exactly what's going wrong:
Couldn't match expected type ‘Maybe b0’ with actual type ‘Bool’
S.mapM expects a function that returns a value in the same Monad as your stream—in your case, that's Maybe. But isJust x spits out a plain Bool, not a Maybe Bool. This type mismatch is why the compiler is throwing a fit.
Solutions
You have two straightforward fixes depending on your goal:
1. Use S.map for Pure Function Transformations
If you just want to convert each Maybe Integer to a Bool (checking if it's a Just), you don't need mapM at all. S.map is made for pure functions (a -> b) and is the right tool here:
#!/usr/bin/env stack import Streaming import qualified Streaming.Prelude as S import Data.Maybe stream :: Stream (Of (Maybe Integer)) Maybe () stream = S.each [Just 1, Just 2, Just 3, Just 4, Just 5] main :: IO () main = do print $ S.map isJust stream print "done"
2. Wrap the Bool in Maybe if You Need mapM
If you specifically need to use mapM (for example, if you later plan to add monadic logic like IO or conditional failure), you can wrap the Bool result in return to lift it into the Maybe Monad:
#!/usr/bin/env stack import Streaming import qualified Streaming.Prelude as S import Data.Maybe stream :: Stream (Of (Maybe Integer)) Maybe () stream = S.each [Just 1, Just 2, Just 3, Just 4, Just 5] main :: IO () main = do print $ S.mapM (\x -> return (isJust x)) stream print "done"
Quick Note on map vs mapM in Streaming
S.map: For pure transformations—takes a functiona -> band applies it to every element in the stream, no Monad required.S.mapM: For monadic transformations—takes a functiona -> m bwheremmatches the stream's underlying Monad, letting you perform actions (like IO, or Maybe-style failure) while transforming elements.
内容的提问来源于stack exchange,提问作者zoran119

