How do I properly define an empty string in haskell?
Solution 1
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 String
s 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 ""
.
Solution 2
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.
bella
Updated on June 04, 2022Comments
-
bella almost 2 years
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"
? -
bella almost 12 yearsThanks alot, I should of seen that!
-
leftaroundabout almost 12 yearsOf course, the empty string literal
""
can also be used in patterns, this function could be writtenfn "" = "empty"; fn _ = "hello"
.