首页 > 解决方案 > Haskell二叉树解析

问题描述

我正在学习如何在 Haskell 中构建和解析二叉树,我发现了一个我不太明白如何工作的程序示例。所以代码是:

module Main where

data TTT aa = Leaf [aa] | Node (TTT aa) (TTT aa)  deriving (Show,Eq);

a :: Num a => Integer -> Integer; 
a x = x^2; 

ff_a :: TTT Integer -> TTT Integer; 
ff_a t = mm a t; 

mm :: (Integer -> Integer) -> TTT Integer -> TTT Integer; 
mm f (Node a1 a2) = Node(mm f a1) (mm f a2); 
mm f (Leaf n) = Leaf(new_mm f n); 

new_mm :: (Integer -> Integer) -> [Integer] -> [Integer]; 
new_mm f (a:a1) = f a : new_mm f a1; 
new_mm f [] = []; 

tree =   
    Node   
        (Node   
            (Node   
                ((Leaf[16,-5,19]))
                ((Leaf[14,24,-55,27]))
            )  
            (Node   
                ((Leaf[37,11,64]))
                ((Leaf[-14,6,29]))
            )  
        )  
        (Node   
            (Node   
                ((Leaf[10,-19,22]))
                ((Leaf[3,4,5,-7]))
            )  
            (Node   
                ((Leaf[31,29,13]))
                ((Leaf[18,38,-4]))
            )  
        )  


main :: IO ();

t0 = tree      
t1 = ff_a tree 

main = do

    print t0;
    print t1;

有人可以向我解释一下真正的功能mmnew_mm工作原理吗?那是什么意思Integer -> IntegerTTT integer -> TTT integer是什么数据类型?

标签: haskelltreebinary

解决方案


OP 中显示的代码无法编译,但很容易修复。更改a为:

a :: Integer -> Integer; 
a x = x^2; 

(顺便说一句,分号是多余的,应该删除。用分号结束每一行并不是惯用的 Haskell。)

有人可以向我解释一下“mm”和“new_mm”的功能是如何工作的吗?

mm取决于new_mm,所以让我们从那里开始。了解 Haskell 代码如何以及做什么的常用方法是在 GHCi 中进行试验。

*Main> new_mm a []
[]
*Main> new_mm a [1,2,3]
[1,4,9]
*Main> new_mm (\i -> i + 1) [1,2,3]
[2,3,4]

new_mm函数根据函数参数转换输入列表中的每个值。它只是从头开始实现的内置map功能,仅限于在Integer. 如果您需要了解map实现的工作原理,我相信您的 Haskell 学习资源包含解释。

mm函数只是“提升”映射函数以处理TTT数据结构。

*Main> mm a (Leaf [])
Leaf []
*Main> mm a (Leaf [1,2,3])
Leaf [1,4,9]
*Main> mm (\i -> i + 1) (Leaf [1,2,3])
Leaf [2,3,4]
*Main> mm (\i -> i + 1) (Node (Leaf [1,2,3]) (Leaf [4,5,6]))
Node (Leaf [2,3,4]) (Leaf [5,6,7])

整数 -> 整数和 TTT 整数 -> TTT 整数是什么意思,那是什么数据类型?

Integer -> Integer表示以 aInteger作为输入并返回 的函数Integer

TTT Integer -> TTT Integer(注意我改变了大小写)同样,它表示一个将TTT Integer值作为输入并返回TTT Integer值的函数。


推荐阅读