Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I properly define an empty string in haskell?

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

like image 320
bella Avatar asked Nov 30 '22 23:11

bella


2 Answers

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.

like image 23
Don Stewart Avatar answered Dec 04 '22 01:12

Don Stewart


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

like image 180
Simeon Visser Avatar answered Dec 04 '22 02:12

Simeon Visser