Search code examples
haskellrecursionabstract-data-type

Implementing a Table ADT in Haskell -why is my minkey function not working?


I have implemented a Table data type in haskell,but my minkey function which is supposed to return the smallest key seems not to give the right result. I am just wondering why..

module Table where
import Prelude hiding (init,read,length)

type Key = Int
type Value = String

errorvalue = "ERROR"

maxentries = 5
data Table = Empty | App(Key,Value,Table)
deriving Show

init   :: Table
insert :: (Key,Value,Table) -> Table 
isin   :: (Key,Table) -> Bool
read   :: (Key,Table) -> Value
empty  :: Table -> Bool
delete :: (Key,Table) -> Table
update :: (Key,Value,Table) -> Table
length :: Table -> Int
full :: Table -> Bool
minkey::Table->Key

init = Empty

minkey(App(k,v,init))=k
minkey(App(k,v,t))= if k>minkey(t) then minkey(t) else k

insert(k,v,t) = if v == errorvalue then t
            else if isin(k,t) then t
    else if full(t) then t
            else App(k,v,t)

isin(x,Empty)      = False
isin(x,App(k,v,t)) = if x == k then True
             else isin(x,t)

read(x,Empty)      = errorvalue
read(x,App(k,v,t)) = if x == k then v
             else read(x,t)

empty(Empty)      = True
empty(App(k,v,t)) = False

delete(x,Empty)      = Empty
delete(x,App(k,v,t)) = if x == k then t
           else App(k,v,delete(x,t))

 update(k,v,Empty)        = Empty
 update(k,v,App(k2,v2,t)) = if k == k2 then App(k,v,t)
           else App(k2,v2,update(k,v,t))

 length(Empty)      = 0
 length(App(k,v,t)) = 1 + length(t)

 full(t) = if length(t) == maxentries then True
      else False

In another script I initialized a table:

 import Table
 import Prelude hiding (init,read,length)

 main :: IO ()

 main = do
 let k1 = 9
 let k2 = 8
 let k3 = 1
 let k4 = 6
 let k5 = 10


 let v1 = "q"
 let v2 = "a"
 let v3 = "si"
 let v4 = "se"
 let v5 = "fu"

 let i0 = init
 let i1 = insert(k1,v1,i0)
 let i2 = insert(k2,v2,i1)
 let i3 = insert(k3,v3,i2)
 let i4 = insert(k4,v4,i3)
 let i5 = insert(k5,v5,i4)  

 let m = minkey(i5)
 print m
 print i5

When I print m the output is not 1 as I expected,but the last key imported to the table (in this case 10) What am I doing wrong? Maybe the recursion?


Solution

  • minkey's init is regarded as argument name, not Empty, so pattern always matches on that line. Maybe GHC might have warned you as -Woverlapping-patterns.

    If init can't be changed, then you may use case expression.