简体   繁体   中英

Couldn't match expected type ‘[Int]’ with actual type ‘Int’ haskell

I'm trying to do an exercise that gives a list of every path of a binary tree from leaf to root

here's my code:

data Tree = Leaf Int | Node (Tree) Int (Tree)

go (Leaf a) = (a : []) : []
go (Node l n r) = insev((go l):(go r)) n

insev :: [[a]] -> a -> [[a]]
insev [[]] x = []
insev (h:t) x = (insb h x) : (insev t x)

insb [] num = num : []
insb (h:t) num = h:(insb t num)

it should be correct from logical perspective but i am new to haskell and i don't know why i get this error

Main.hs:21:19: error:
    • Couldn't match type ‘[Int]’ with ‘Int’
      Expected: [[Int]]
        Actual: [[[Int]]]
    • In the expression: insev ((go l) : (go r)) n
      In an equation for ‘go’:
          go (Node l n r) = insev ((go l) : (go r)) n
   |
21 | go (Node l n r) = insev ((go l):(go r)) n
   |                   ^^^^^^^^^^^^^^^^^^^^^^^

Main.hs:21:34: error:
    • Couldn't match type ‘Int’ with ‘[Int]’
      Expected: [[[Int]]]
        Actual: [[Int]]
    • In the second argument of ‘(:)’, namely ‘(go r)’
      In the first argument of ‘insev’, namely ‘((go l) : (go r))’
      In the expression: insev ((go l) : (go r)) n
   |
21 | go (Node l n r) = insev ((go l):(go r)) n
   |                                  ^^^^

Main.hs:21:41: error:
    • Couldn't match expected type ‘[Int]’ with actual type ‘Int’
    • In the second argument of ‘insev’, namely ‘n’
      In the expression: insev ((go l) : (go r)) n
      In an equation for ‘go’:
          go (Node l n r) = insev ((go l) : (go r)) n
   |
21 | go (Node l n r) = insev ((go l):(go r)) n

Without even looking at the rest of the code, this is never * going to fly:

(go l) : (go r)

Presumably go is returning something of the same type in both calls, but the arguments to (:) must have different types:

(:) :: a -> [a] -> [a]

Perhaps you want (++) instead, whose arguments must have the same types:

(++) :: [a] -> [a] -> [a]

* Okay, yes, it is possible to write go in a way that invalidates the next sentence's assumption that it is returning the same type in both calls. But that's a pretty unusual situation to be in, and one you have to pretty consciously try to arrive at.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM