0

同じ番号を持つ 2 つのノードがないように、フォレストの各ノードに番号を割り当てようとします。相互に再帰的に呼び出す 2 つの関数を使用しようとしましたが、コンパイル エラーが発生します。コードは次のとおりです。

numberTree :: Int -> Tree a -> (Tree Int,Int)

numberTree n (Node c []) = (Node n [], n+1)
numberTree n (Node _ (x:xs)) =  (Node n  fst.numberForest  (n+1) xs, snd.numberForest   (n+1) xs)


numberForest :: Int -> [Tree a] -> ([Tree Int],Int)

numberForest n (x:xs) = ((fst(numberTree n x )):(fst(numberForest (n+1) xs)), snd(numberForest (n+1) xs)+1)

numberForest n (x:xs) = ((fst(numberTree n x )):(fst(numberForest (n+1) xs)), snd(numberForest (n+1) xs)+1)

私が得るエラーは次のとおりです。

.hs:27:34: 予想される型b0 -> c0' with actual typeTree Int と一致しませんでした 考えられる原因: Node' is applied to too many arguments In the first argument of(.)​​'、つまり `Node n fst' 式: Node n fst 。数の森 (n + 1) xs

.hs:27:34:
Couldn't match expected type `Tree Int' with actual type `a0 -> c0
In the expression: Node n fst . numberForest (n + 1) xs
In the expression:
  (Node n fst . numberForest (n + 1) xs,
   snd . numberForest (n + 1) xs)
In an equation for `numberTree':
    numberTree n (Node _ (x : xs))
      = (Node n fst . numberForest (n + 1) xs,
         snd . numberForest (n + 1) xs)

 .hs:27:42:
Couldn't match type `(a1, b1) -> a1' with `[Tree Int]'
Expected type: Forest Int
  Actual type: (a1, b1) -> a1
Probable cause: `fst' is applied to too few arguments
In the second argument of `Node', namely `fst'
In the first argument of `(.)', namely `Node n fst'

 .hs:27:46:
Couldn't match expected type `a0 -> b0'
            with actual type `([Tree Int], Int)'
Possible cause: `numberForest' is applied to too many arguments
In the second argument of `(.)', namely `numberForest (n + 1) xs'
In the expression: Node n fst . numberForest (n + 1) xs

.hs:27:70:
Couldn't match expected type `Int' with actual type `a2 -> c1'
In the expression: snd . numberForest (n + 1) xs
In the expression:
  (Node n fst . numberForest (n + 1) xs,
   snd . numberForest (n + 1) xs)
In an equation for `numberTree':
    numberTree n (Node _ (x : xs))
      = (Node n fst . numberForest (n + 1) xs,
         snd . numberForest (n + 1) xs)

.hs:27:74:
Couldn't match expected type `a2 -> (a3, c1)'
            with actual type `([Tree Int], Int)'
Possible cause: `numberForest' is applied to too many arguments
In the second argument of `(.)', namely `numberForest (n + 1) xs'
In the expression: snd . numberForest (n + 1) xs

何が問題で、どうすれば解決できますか?

4

2 に答える 2

0

状態モナドはあなたの友達です。

import Control.Monad.Trans.State

data Tree   a = Node a (Forest a)
type Forest a = [Tree a]

numberTreeS :: Tree a -> State Int (Tree Int)
numberTreeS (Node _ xs) = do
    n <- get
    put (n + 1)
    xs' <- numberForestS xs
    return $ Node n xs'

numberForestS :: Forest a -> State Int (Forest Int)
numberForestS = mapM numberTreeS

numberForest :: Forest a -> Forest Int
numberForest xs = evalState (numberForestS xs) 0

これは、明示的な状態の受け渡しよりも読みやすいです。

于 2014-12-11T16:52:17.027 に答える