下面是使用反应式香蕉库的Haskell FRP程序示例。我只是刚刚开始对Haskell感觉如何,特别是没有把我的头脑放在FRP的含义上。我会很感激下面我是否在使用反应式香蕉?
{-# LANGUAGE DeriveDataTypeable #-}
module Main where
{-
Example FRP/zeromq app.
The idea is that messages come into a zeromq socket in the form "id state". The state is of each id is tracked until it's complete.
-}
import Control.Monad
import Data.ByteString.Char8 as C (unpack)
import Data.Map as M
import Data.Maybe
import Reactive.Banana
import System.Environment (getArgs)
import System.ZMQ
data Msg = Msg {mid :: String, state :: String}
deriving (Show, Typeable)
type IdMap = Map String String
-- | Deserialize a string to a Maybe Msg
fromString :: String -> Maybe Msg
fromString s =
case words s of
(x:y:[]) -> Just $ Msg x y
_ -> Nothing
-- | Map a message to a partial operation on a map
-- If the 'state' of the message is "complete" the operation is a delete
-- otherwise it's an insert
toMap :: Msg -> IdMap -> IdMap
toMap msg = case msg of
Msg id_ "complete" -> delete id_
_ -> insert (mid msg) (state msg)
main :: IO()
main = do
(socketHandle,runSocket) <- newAddHandler
args <- getArgs
let sockAddr = case args of
[s] -> s
_ -> "tcp://127.0.0.1:9999"
putStrLn ("Socket: " ++ sockAddr)
network <- compile $ do
recvd <- fromAddHandler socketHandle
let
-- Filter out the Nothings
justs = filterE isJust recvd
-- Accumulate the partially applied toMap operations
counter = accumE M.empty $ (toMap . fromJust <$> justs)
-- Print the contents
reactimate $ fmap print counter
actuate network
-- Get a socket and kick off the eventloop
withContext 1 $ \ctx ->
withSocket ctx Sub $ \sub -> do
connect sub sockAddr
subscribe sub ""
linkSocketHandler sub runSocket
-- | Recieve a message, deserialize it to a 'Msg' and call the action with the message
linkSocketHandler :: Socket a -> (Maybe Msg -> IO()) -> IO()
linkSocketHandler s runner = forever $ do
receive s [] >>= runner . fromString . C.unpack
代码的一些批评有一个要点这里:https://gist.github.com/1099712。
我特别欢迎任何关于这是否是“好”使用accumE的评论,(我不清楚这个函数每次都会遍历整个事件流,尽管我猜测不到)。
另外我想知道如何从多个套接字中获取消息 - 目前我有一个永久的事件循环。作为一个具体的例子,我将如何添加第二个套接字(用zeromq说法的REQ/REP对)来查询计数器内的IdMap的当前状态?
感谢海因里希,原因是在FRP看起来很合适,如果你有很多zeromq套接字,他们可以非常容易地开始像一个GUI的事件驱动输入...所以我尽管我会踢一些新的想法轮胎:-) 你认为用State monad和haskell线程做这件事更有意义吗? –
@Ben Ford:我在答案中加了一个小小的评论。我不知道你想用套接字做什么,所以我不能告诉你FRP是否为你的目的矫枉过正。基本上,如果你的事件网络不会比单独的'accumE'和一些'filterE'大得多,那么在没有FRP的情况下它会更加优雅。 –