You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用streaming库对生成的流值应用函数?(报错求助)

Fixing the Type Mismatch with Streaming's 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 function a -> b and applies it to every element in the stream, no Monad required.
  • S.mapM: For monadic transformations—takes a function a -> m b where m matches the stream's underlying Monad, letting you perform actions (like IO, or Maybe-style failure) while transforming elements.

内容的提问来源于stack exchange,提问作者zoran119

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:29:57