Home > Enterprise >  GHCi freezes if I try to run a simple binTree
GHCi freezes if I try to run a simple binTree

Time:12-27

I started to learn Haskell as a new language just because I can. As a practice I tried to code a simple BinTree but I'm running in a quite infuriating error.

This is the sourcecode I'm having trouble with:


data Tree = Node Tree Int Tree
    | Empty
    deriving (Eq,Show)
    
addNode :: Tree -> Int -> Tree
addNode Empty a = Node Empty a Empty
addNode (Node left a right) b   | a > b = Node (addNode left b) a right
                                | a < b = Node left a (addNode right b)
                                | otherwise = Node left b right

Note: I tried running the code with GHC 8.10.7 and GHC 9.2.1 but to no avail.

The Problem happens as I'm trying to run addNode on an Empty binTree test. Creating the empty binTree with test = Empty and checking it with just test works out fine and gives me Empty as an result, but if I then try to add a node to test with test = addNode test <Int> and try to show me the result of test nothing happens. The compiler is trying to run the code, but it just freezes and I have to reopen PowerShell.

If it helps, this is my current setup:

GHC 9.2.1 | 8.10.7 cabal 3.6.2.0 HLS 1.5.1 Stack 2.7.3 OS Win10

CodePudding user response:

By running test = addNode test 5, you weel keep adding 5 for an infinite amount of times. It does not take the "old" test. In Haskell a variable is always immutable, if you use test in the "body" of the definition, then it will use the variable you are defining. It works thus as a recursive let statement [wiki].

Here it thus means that you define test as:

let test be the result of adding <Int> to test.

and this will thus result in trying to add that integer value for an infinite amount of times, since it means test is adding <Int> to a tree that has add <Int> that has added <Int> that …

You can define a new variable and use the old tree with:

test2 = addNode test 5
  • Related