我的程序出了问题,我能够找出问题所在。我设法将它减少到这个更简单的问题。让我们说我有功能
fn:: String -> String
fn (x:xs)
| null (x:xs) = "empty"
| otherwise = "hello"
输入随机内容会返回"hello"
,但如果我这样做,
fn ""
我得到了非详尽的模式错误。由于“”应该是一个空列表,[]
,它不应该与我的第一个模式匹配并返回"empty"
吗?
答案 0 :(得分:8)
Haskell中的String
是一个字符列表。因此,要匹配空String
,您需要匹配一个空列表([]
)。您的模式(x:xs)
只会将列表或String
与至少一个元素匹配,因为它包含一个元素(x
)和其余元素(xs
),这可能是空的或非空的。
您的函数的工作版本如下所示:
fn :: String -> String
fn [] = "empty"
fn (x:xs) = "hello"
这将为"empty"
返回fn ""
。
答案 1 :(得分:7)
你的功能
fn:: String -> String
fn (x:xs)
| null (x:xs) = "empty"
| otherwise = "hello"
最好写成:
fn :: String -> String
fn x | null x = "empty"
| otherwise = "hello"
或
fn :: String -> String
fn "" = "empty"
fn _ = "hello"
因为null (x:xs)
肯定是错的(总是假的)。
我更喜欢后者,因为它表明你只关心String类型。
虽然这是一个有点奇怪的功能。我在实践中没有看到它。