How do I properly define an empty string in haskell?

16,250

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 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 "".

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.

Share:
16,250
bella
Author by

bella

Updated on June 04, 2022

Comments

  • bella
    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
    bella almost 12 years
    Thanks alot, I should of seen that!
  • leftaroundabout
    leftaroundabout almost 12 years
    Of course, the empty string literal "" can also be used in patterns, this function could be written fn "" = "empty"; fn _ = "hello".