如果您不能在Haskell中更改变量的值,那么您如何创建数据结构? [英] If you can't change a variable's value in Haskell, how do you create data structures?

查看:154
本文介绍了如果您不能在Haskell中更改变量的值,那么您如何创建数据结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我有下面的代码创建了一个二叉搜索树,但是如果我希望它用用户输入动态创建和更改,我这样做,如果我不能改变haskell中的变量的值?!?

  find ::(Ord a) =>节点a  - > a  - > Bool 
find(Node val左边)s
| s == val = True
| s< val =找到剩下的
| s> val =查找正确s

查找空s = False

数据节点a =节点a(节点a)(节点a)
|清空

myTree =节点m(节点a清空)
(节点z清空)

在此先感谢!

解决方案

纯粹功能性数据结构背后的想法是计算新值,而不是改变它们,并将它们传递给参数,而不是全局存储。



所以给定一个函数

  insert :: Ord a =>节点a  - > a  - >节点a 

你的程序看起来像这样

   - 让用户输入存储在树结构中的k值
addTreeItems :: Int - >节点Int - > IO(Node Int)
addTreeItems 0 tree =返回树
addTreeItems k树= do
putStr输入新项目:
item< - readLn
addTreeItems( k - 1)(插入树项) - 递归地传递树

main = do
tree< - addTreeItems 10空
- ...

使用monadic helper函数,可以简化为像

 (foldl insert Empty)`liftM`(sequence $ replicate k(putStrEnter new item:>> readLn))

如果你想更新某个位置的值,你需要更高级的数据结构,比如 zipper ,但仍然是纯粹的功能!


As per the title.

I have the following code which creates a binary search tree, but if I want it created and changed dynamically with user input, how would I do that if I can't change the value of a variable in 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)

Thanks in advance!

解决方案

The idea behind purely functional data structures is to compute new values instead of changing them and to pass them (recursively) in parameters instead of storing them globally.

So given a function

insert :: Ord a => Node a -> a -> Node a

your programm could look like this

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

Using monadic helper functions, this could be simplified to things like

(foldl insert Empty) `liftM` (sequence $ replicate k (putStr "Enter new item: " >> readLn))

If you want to update values at a certain position, you'll need more advanced datastructures like a zipper, that are nevertheless still purely functional!

这篇关于如果您不能在Haskell中更改变量的值,那么您如何创建数据结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆