正如标题所示。
我有以下创建二叉搜索树的代码,但如果我希望它根据用户输入动态创建和更改,如果我无法更改 haskell 中变量的值,我该怎么做?!?
find :: (Ord a) => Node a -> a -> Bool
find (Node val left right) s
| s == val = True
| s < val = find left s
| s > val = find right s
find Empty s = False
data Node a = Node a (Node a) (Node a)
| Empty
myTree = Node "m" (Node "a" Empty Empty)
(Node "z" Empty Empty)
提前致谢!
纯函数数据结构背后的想法是计算新值而不是更改它们,并在参数中(递归地)传递它们而不是全局存储它们。
所以给定一个函数
insert :: Ord a => Node a -> a -> Node a
你的程序可能是这样的
-- Let the user enter k values that are stored in a tree structure
addTreeItems :: Int -> Node Int -> IO (Node Int)
addTreeItems 0 tree = return tree
addTreeItems k tree = do
putStr "Enter new item: "
item <- readLn
addTreeItems (k - 1) (insert tree item) -- Recursively pass the tree
main = do
tree <- addTreeItems 10 Empty
-- ...
使用一元辅助函数,这可以简化为类似的事情
(foldl insert Empty) `liftM` (sequence $ replicate k (putStr "Enter new item: " >> readLn))
如果您想更新某个位置的值,您将需要更高级的数据结构,例如zipper http://en.wikibooks.org/wiki/Haskell/Zippers,但仍然是纯功能性的!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)