0
data Tree = EmptyTree | Node Integer Tree Tree deriving (Show, Eq, Ord)

insertElement x EmptyTree = Node x EmptyTree EmptyTree -- BASE CASE
insertElement x (Node a left right) = if x == a -- DO NOTHING
    then (Node x left right)
    else if x < a -- INSERT TO LEFT
    then (Node a (insertElement x left) right)
    else -- INSERT TO RIGHT
    Node a left (insertElement x right)

inserter (x:list) = insertElement x (insertElement (inserter (list)) (EmptyTree))

I have got the above Haskell Code. The inserter function is supposed to return a tree when we give a list to it. Everything other than inserter works perfectly fine. When I try to :r this file, it gives me the error

Couldn't match type `Tree' with `Integer'
    Expected type: [Integer] -> Integer
      Actual type: [Integer] -> Tree

What should I change about the inserter function?

leftaroundabout
  • 117,950
  • 5
  • 174
  • 319
malai_320
  • 21
  • 2

1 Answers1

2
insertElement :: Integer -> Tree -> Tree
inserter :: [Integer] -> Tree
inserter (x:list) = insertElement x (insertElement (inserter (list)) (EmptyTree))
--                                                  ^^^^^^^^^^^^^^^
-- Assuming the signatures are as above, the problem is ^ here

Your insertElement expects an Integer as first argument but you provide a Tree

You can change the definition of inserter to the following:

insereter :: [Integer] -> Tree
inserter [] = EmptyTree
inserter (x:list) = insertElement x $ inserter list
cafce25
  • 15,907
  • 4
  • 25
  • 31
  • Thanks for your response. What does '$' mean in the code you wrote? – malai_320 Mar 27 '23 at 12:36
  • 1
    `$` is just [function application with a low precedence](https://stackoverflow.com/questions/19521246/what-does-mean-do-in-haskell). – cafce25 Mar 27 '23 at 12:45
  • 4
    @malai_320 `insertElement x $ inserter list` simply means `insertElement x (inserter list)` – chi Mar 27 '23 at 13:11