gpt4 book ai didi

haskell - 在 Haskell 程序之间传递数据

转载 作者:行者123 更新时间:2023-12-02 21:08:57 26 4
gpt4 key购买 nike

我正在 Haskell 中编写两个程序,其中一个提供了一棵充满值的树。

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

例如,我执行 ./Generate ,它会保存树的值。然后我执行 ./Work 它会使用树的值。有人可以帮我吗?

最佳答案

最简单的方法可能是

data MyData = ... deriving (Read, Show)

制作人

makeMyData :: MyData
makeMyData = ....

main = writeFile "output.data" (show makeMyData)

消费者

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

main = readFile "output.data" >>= ioUseMyData . read

您可以使用 getContentsputStrLn 来使用标准输入/输出。

完整示例:

-- 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

结果

Tree with 3 nodes

更换

writeFile "output.data" (show makeTree)

print makeTree

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

getContents >>= ioUseTree . read

您可以使用管道(bashcmd.exe、...)

$ ./producer | ./consumer
Tree with 3 nodes

关于haskell - 在 Haskell 程序之间传递数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30433041/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com