我想用标准ML制作功能maptree

时间:2016-05-02 15:25:17

标签: sml smlnj

我想用标准ML制作函数maptree。 如果函数f(x)= x + 1; 然后

+""

应该是结果

maptree(f, NODE(NODE(LEAF 1,LEAF 2),LEAF 3));

我写下面的代码。

NODE(NODE(LEAF 2,LEAF 3),LEAF 4))

但当我像这样执行此代码时

datatype 'a tree = LEAF of 'a | NODE of 'a tree * 'a tree;
fun f(x) = x + 1;
fun maptree(f, NODE(X, Y)) = NODE(maptree(f, X), maptree(f, Y))
| maptree(f, LEAF(X)) = LEAF(f X);

结果不是我想要的 (NODE(NODE(LEAF 2,LEAF 3),LEAF 4))) 但 NODE(NODE(LEAF#,LEAF#),LEAF 4))。 为什么会这样(不是数字而是#)?

2 个答案:

答案 0 :(得分:4)

当打印的数据结构比预设值更深时,REPL使用

#。如果您增加该值,您将获得除外的结果。我假设您正在使用SML / NJ,它调用该设置print.depth

sml -Cprint.depth=20
- maptree(f, (NODE(NODE(LEAF 1,LEAF 2),LEAF 3)));
val it = NODE (NODE (LEAF 2,LEAF 3),LEAF 4) : int tree

您可以通过执行sml -H找到更多此类选项。在“编译器打印设置”部分下查找它们:

compiler print settings:
     print.depth                                          (max print depth)
     print.length                                        (max print length)
     print.string-depth                            (max string print depth)
     print.intinf-depth                        (max IntInf.int print depth)
     print.loop                                                (print loop)
     print.signatures                       (max signature expansion depth)
     print.opens                                             (print `open')
     print.linewidth                   (line-width hint for pretty printer)

答案 1 :(得分:0)

一些意见:

  1. 我可能会使用定义

    datatype 'a tree = Leaf | Node of 'a tree * 'a * 'a tree
    

    这样也可以表示具有零个或两个元素的树。

  2. 我可能会讨论树图功能

    fun treemap f Leaf = Leaf
      | treemap f (Node (l, x, r)) = Node (treemap f l, x, treemap f r)
    

    因为您可以部分应用它,例如像:

    (* 'abstree t' returns t where all numbers are made positive *)
    val abstree = treemap Int.abs
    
    (* 'makeFullTree n' returns a full binary tree of size n *)
    fun makeFullTree 0 = Leaf
      | makeFullTree n =
        let val subtree = makeFullTree (n-1)
        in Node (subtree, n, subtree)
        end
    
    (* 'treetree t' makes an int tree into a tree of full trees! *)
    val treetree = treemap makeFullTree
    
  3. 您可能在某些时候也希望fold a tree

相关问题