2016-05-02 7 views
3

標準MLで関数maptreeを作りたいです。 関数f(x)= x + 1; その後、標準MLで関数maptreeを作りたい

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); 

私はこの

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

結果は私は (NODE(ノード(リーフ2、LEAF 3)、LEAF 4))) しかし ノードにたくされないように、このコードを実行します(NODE(リーフ#、リーフ#)、リーフ4))。 これはなぜ発生しましたか(数字ではなく#)。

答えて

4

#は、印刷するデータ構造がプリセット値よりも深い場合にREPLによって使用されます。その値を大きくすると、除外した結果が得られます。

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を実行することにより、これらのようなより多くのオプションを見つけることができます:私はあなたがprint.depthを設定することを呼び出しますSML/NJを、使用していると仮定します。

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) 
0

いくつかのコメント:「コンパイラの印刷設定」セクションの下にそれらを見上げる木々よう

  1. 私はおそらくゼロまたは2で定義

    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にしたいことがあります。