【问题标题】:Tree size in haskellHaskell中的树大小
【发布时间】:2018-01-04 00:39:10
【问题描述】:

我有一个这样的树的实现:

数据树 a = 空 |节点a[树a]派生Show

我需要得到尺寸。

我认为这段代码可以解决这个问题,但我有一个错误:

size :: Tree a -> Int
size Empty       = 0
size (Node a ts) = 1 + [size t | t<-ts]

【问题讨论】:

  • 您正在尝试添加一个数字和一个列表。你能想出一种方法来sum列表中的数字吗?
  • 但是这种列表返回一个int no?
  • 没有“返回” int 的列表。列表就是列表。
  • 我认为您应该首先定义大小的含义。是树的深度、元素的数量还是别的什么?
  • 关于您的问题,您不应该发布带​​注释的代码。你应该给我们你的错误信息。

标签: haskell


【解决方案1】:

提示:

> 1 + [2,3,4]
<interactive>:8:1: error:
    • Non type-variable argument in the constraint: Num [t]
      (Use FlexibleContexts to permit this)
    • When checking the inferred type
        it :: forall t. (Num [t], Num t) => [t]

> 1 + sum [2,3,4]
10

【讨论】:

    【解决方案2】:
    size:: Tree a -> Int
    size Empty = 0
    size (Node a ts) = 1 + maximum[size t | t <- ts]
    

    可能你想要子树的最大大小,所以我会在将每个分支转换为他的大小后使用函数预定义的最大值来获取它。

    【讨论】:

    • 这是深度,最大。
    【解决方案3】:

    您的代码中显然有输入错误。

    Couldn't match expected type ‘Int’ with actual type ‘[Int]’
    • In the expression: 1 + [size t | t <- ts]
      In an equation for ‘size’:
          size (Node a ts) = 1 + [size t | t <- ts]
    

    既然你想要一个Int,你必须想办法把你的Int列表转换成Int

    换句话说,你可以像这样引入一个洞:

    size :: Tree a -> Int
    size Empty         = 0
    size (Node a ts) = 1 + _g [size t | t<-ts]  
    

    导致错误信息:

    • Found hole: _g :: [Int] -> Int
      Or perhaps ‘_g’ is mis-spelled, or not in scope
    • In the expression: _g
      In the second argument of ‘(+)’, namely ‘_g [size t | t <- ts]’
      In the expression: 1 + _g [size t | t <- ts]
    • Relevant bindings include
        ts :: [Tree a]
          (bound at /Users/jeeb/incubator/scratch/app/Main.hs:10:14)
        a :: a (bound at /Users/jeeb/incubator/scratch/app/Main.hs:10:12)
        size :: Tree a -> Int
          (bound at /Users/jeeb/incubator/scratch/app/Main.hs:9:1)
    

    根据您所说的“大小”,您应该能够用正确的函数替换 g

    【讨论】:

      猜你喜欢
      • 2017-02-09
      • 1970-01-01
      • 2014-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-29
      • 1970-01-01
      • 2012-05-18
      相关资源
      最近更新 更多