如何将外部导出函数的参数传递给Pipe?

时间:2013-12-11 04:22:55

标签: haskell haskell-pipes

我有一个

foreign export stdcall tick :: Integer -> Float -> Float -> IO Int

在每次调用此函数时,我希望将其参数传递给haskell管道库中的一组管道。

在调用之间,我不希望管道忘记最后10次调用的最小和最大参数。

我该怎么做?

1 个答案:

答案 0 :(得分:1)

这是pipes-concurrency旨在做的许多事情之一。你所做的是spawn一个缓冲区,每次调用派生的tick函数时,它都会将其参数填充到该缓冲区中。然后你可以得到一个管道流,从那个缓冲区出来的所有东西。

import Control.Concurrent.Async
import Pipes
import Pipes.Concurrent
import qualified Pipes.Prelude as P

-- Your FFI tick function, which we will wrap with a derived function
ffi_tick :: Integer -> Float -> Float -> IO Int
ffi_tick _ _ _ = return 0

-- A data structure just to simplify the types
-- In theory I could have just used a tuple
data Ticker = Ticker
    { _tick  :: Integer -> Float -> Float -> IO Int
    , _input :: Input (Integer, Float, Float)
    }

-- This is in charge of buffer initialization and deriving the new
-- tick function
makeTicker :: IO Ticker
makeTicker = do
    (output, input) <- spawn Unbounded
    let tick x y z = do
            atomically $ send output (x, y, z)
            ffi_tick x y z
    return (Ticker tick input)

-- This is example code showing how you would use it    
main = do
    Ticker tick input <- makeTicker
    a <- async $ runEffect $ fromInput input >-> P.print
    tick 1 2.0 3.0
    tick 4 5.0 6.0
    tick 7 8.0 9.0
    wait a