haskell - 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;
有人可以向我解释一下真正的功能mm
和new_mm
工作原理吗?那是什么意思Integer -> Integer
,TTT integer -> TTT integer
是什么数据类型?
解决方案
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
值的函数。
推荐阅读
- javascript - 堆叠 div 的内部内容在 Firefox 中无法正常工作
- java - Spring MVC 应用程序不适用于最新的 Java 11 版本(Amazon corretto 11 [11.0.11.9.1])
- javascript - e.preventDefault 和计时器无法阻止甜蜜警报弹出框在不到 1 秒内消失
- javascript - 开玩笑“意外令牌”导入 ES6 模块
- git - 无法推送到 github 私人仓库
- android - Mockito 升级 3.10 到 3.11 导致崩溃
- firebase - React Native Firebase - 何时设置 UserId 和 UserProperties
- javascript - iframe 在 express js 中无法正常工作
- flutter - 颤振字符串空间在电子邮件中显示 +
- 3d - 定义多边形的绘制顺序