簡體   English   中英

Haskell:[IO()]到IO()

[英]Haskell: [IO ()] to IO ()

Haskell wiki有以下問題:

https://en.wikibooks.org/wiki/Haskell/Higher-order_functions for :: a -> (a -> Bool) -> (a -> a) -> (a -> IO ()) -> IO () for ipf job = -- ???

我能夠提出以下實現:

generate :: a -> (a->Bool) -> (a->a) -> [a]
generate s cnd incr = if (cnd s) then [] else [s] ++ generate (incr s) cnd incr

-- collapse :: [IO ()] -> IO ()
-- collapse (x:xs) = x ++ collapse xs
-- does not work ^^^^^^


for::a->(a->Bool)->(a->a)->(a->IO())->IO()
for s cnd incr ioFn = map (ioFn) (generate s cnd incr)

當然map (ioFn) (generate s cnd incr)導致[IO ()] 我不知道如何將其轉換為IO ()我需要像foldl這樣的東西,而不是[IO ()]而不是[a]

您正在尋找的功能是:

sequence_ :: (Foldable t, Monad m) => t (m a) -> m ()

但實際上我們可以只替換map ,這樣我們就不需要額外的功能了。 你可以在這里使用mapM_ :: Monad m => (a -> mb) -> [a] -> m ()而不是map ,所以:

for :: a -> (a -> Bool) -> (a -> a) -> (a -> IO ()) -> IO()
for s cnd incr ioFn = mapM_ ioFn (generate s cnd incr)

因此,將函數ioFun應用於generate s cnd incr所有元素,並最終返回unit ()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM