I'm trying to understand time complexity of pattern matching. I thought matching types like in foo would take constant time while matching patterns like in bar would take O(n) but I couldn't figure it out by going step-by-step with debugger.
module Main where
data Foo = Bar | Baz | Cat
main :: IO ()
main =
do
print $ foo Baz
line <- getLine
let x = read line :: Int
print $ bar [x,2,3]
-- Constructors of Foo known in advance
-- So this can be a jump table
foo :: Foo -> Int
foo Bar = 1
foo Baz = 2
foo Cat = 3
-- Elements of list can't be known in advance
-- So this should take O(n) ???
bar :: [Int] -> Int
bar [] = 0
bar (x:[]) = 1
bar (1:x:xs) = 2
bar (y:x:xs) = 3
What's the time complexity of this patterns?
[]will match in O(1), since it simply checks if the data constructor is[]. For(x:[]), it will take two checks, first it will check if the outer data constructor is(:), and then that the second parameter is the[]. For(1:x:xs)and(y:x:xs), it will also take two steps. So even if the list contains thousands of elements, it will not check all these elements.