I'm having a problem with my program and I was able to isolate the problem. I managed to reduce it to this simpler problem. Lets say I have the function
fn:: String -> String
fn (x:xs)
| null (x:xs) = "empty"
| otherwise = "hello"
Typing in random stuff returns "hello" but if I do,
fn ""
I get the non-exhaustive pattern error. Since "" is suppose to be an empty list, [], shouldn't it match to my first pattern and return "empty"?
Your function
fn:: String -> String
fn (x:xs)
| null (x:xs) = "empty"
| otherwise = "hello"
would be better written as:
fn :: String -> String
fn x | null x = "empty"
| otherwise = "hello"
or
fn :: String -> String
fn "" = "empty"
fn _ = "hello"
Since null (x:xs) is certainly wrong (always False).
I prefer the latter, since it makes clear you care only for String types.
This is a slightly weird function though. I haven't seen it in practice.
A String in Haskell is a list of characters. So to match the empty String you need to match an empty list ([]). Your pattern (x:xs) will only match lists or Strings with at least one element because it consists of one element (x) and the rest (xs), which could be empty or non-empty.
A working version of your function would look like this:
fn :: String -> String
fn [] = "empty"
fn (x:xs) = "hello"
This will return "empty" for fn "".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With