Tree 二叉树字符数和concat
二叉树在ocaml中具有“A树”类型,如下所示:Tree 二叉树字符数和concat,tree,ocaml,binary-tree,Tree,Ocaml,Binary Tree,二叉树在ocaml中具有“A树”类型,如下所示: type 'a tree = Leaf of 'a | Fork of 'a * 'a tree * 'a tree let t3 = Fork ("Hello", Leaf "World", Leaf "!") 如何编写一个函数t_charcount,该函数以字符串树作为输入,并计算值包含的字符总数。函数的类型是:字符串树->int t_charcount t3 gives int = 11. 如何编写函数: 编
type 'a tree = Leaf of 'a
| Fork of 'a * 'a tree * 'a tree
let t3 = Fork ("Hello", Leaf "World", Leaf "!")
如何编写一个函数t_charcount,该函数以字符串树作为输入,并计算值包含的字符总数。函数的类型是:字符串树->int
t_charcount t3 gives int = 11.
如何编写函数:
编写一个函数t_concat,将字符串树的值连接在一起。此函数的类型为:字符串树->字符串
t_concat t3 gives string = "HelloWorld!".
如何编写一个函数t_charcount,该函数以字符串树作为输入,并计算值包含的字符总数
使用结构归纳法-考虑基本情况,例如,叶节点中有多少个字符,然后考虑如何连接Fork节点中左右子树的结果,这是您的基本框架:
let t_charcount tree =
let rec loop tree sum = match tree with
| Leaf x -> ...base case...
| Fork (x,t1,t2) -> ...induction case.. in
loop tree 0
编写一个函数t_concat,将字符串树的值连接在一起。此函数的类型为:字符串树->字符串
t_concat t3 gives string = "HelloWorld!".
您应该使用与charcount函数相同的方法,除了使用串联运算符^将结果累积到字符串中而不是将结果累积到整数中
别指望别人会帮你做作业 我是否必须使用String.length函数来计算字符数?我需要一个助手函数吗?另外,我不确定sum的用途是什么?sum是一个任意选择的函数参数名称,您将在其中累积树上的字符总数。是的,您应该使用String.length函数。