在Haskell中的程序之间传递数据

Asd*_*ren 2 tree haskell compilation

我在Haskell中做了两个程序,其中一个程序提供了一个充满值的树.

另一个程序必须现在填充相同的树.我搜索过它,但我还没有找到关于如何做类似事情的事情.

例如,我执行./Generate并使用值保存树.然后我执行./Work并使用树的值.有人能帮帮我吗?

jos*_*uan 5

最简单的方法可能是

data MyData = ... deriving (Read, Show)
Run Code Online (Sandbox Code Playgroud)

制片人

makeMyData :: MyData
makeMyData = ....

main = writeFile "output.data" (show makeMyData)
Run Code Online (Sandbox Code Playgroud)

消费者

ioUseMyData :: MyData -> IO ()
ioUseMyData myData = ....

main = readFile "output.data" >>= ioUseMyData . read
Run Code Online (Sandbox Code Playgroud)

您可以使用getContents和使用标准输入/输出putStrLn.

完整的例子:

-- probably as module
data Tree = Node { value :: Int
                 , left  :: Tree
                 , right :: Tree
                 }
          | Empty
            deriving (Read, Show)

-- your producer program
producerProgram = do

    let makeTree = Node 3 (Node 5 Empty Empty) (Node 7 Empty Empty)
    writeFile "output.data" (show makeTree)

-- your consumer program
consumerProgram = do

    let ioUseTree t = do

            let countNodes Empty = 0
                countNodes (Node _ l r) = 1 + countNodes l + countNodes r

            putStrLn $ "Tree with " ++ show (countNodes t) ++ " nodes"

    readFile "output.data" >>= ioUseTree . read

-- simulate call both
main = do

    -- produce
    producerProgram

    -- consume
    consumerProgram
Run Code Online (Sandbox Code Playgroud)

结果

Tree with 3 nodes
Run Code Online (Sandbox Code Playgroud)

更换

writeFile "output.data" (show makeTree)
Run Code Online (Sandbox Code Playgroud)

通过

print makeTree
Run Code Online (Sandbox Code Playgroud)

readFile "output.data" >>= ioUseTree . read
Run Code Online (Sandbox Code Playgroud)

通过

getContents >>= ioUseTree . read
Run Code Online (Sandbox Code Playgroud)

你可以使用管道(bash,cmd.exe,...)

$ ./producer | ./consumer
Tree with 3 nodes
Run Code Online (Sandbox Code Playgroud)