Haskell: monadic takeWhile?

前端 未结 5 927
一整个雨季
一整个雨季 2020-12-30 07:33

I have some functions written in C that I call from Haskell. These functions return IO (CInt). Sometimes I want to run all of the functions regardless of what

5条回答
  •  囚心锁ツ
    2020-12-30 08:19

    I don't think there is anything like a takeWhileM in the standard library, but you could write it yourself so that only as much IO as needed is executed:

    takeWhileM :: (Monad m) => (a -> Bool) -> [m a] -> m [a]
    takeWhileM _ [] = return []
    takeWhileM p (a:as) =
       do v <- a
          if p v
             then do vs <- takeWhileM p as
                     return (v:vs)
             else return []
    

    The supplied list is only evaluated until an element is found, that doesn't match the predicate:

    *Main> takeWhileM (<4) (map f [1..5])
    1
    2
    3
    4
    [1,2,3]
    

提交回复
热议问题