Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
String 如何在haskell中正确定义空字符串?_String_List_Function_Haskell_Functional Programming - Fatal编程技术网

String 如何在haskell中正确定义空字符串?

String 如何在haskell中正确定义空字符串?,string,list,function,haskell,functional-programming,String,List,Function,Haskell,Functional Programming,我的程序有问题,我能够找出问题所在。我设法把它简化成这个更简单的问题。假设我有这个功能 fn:: String -> String fn (x:xs) | null (x:xs) = "empty" | otherwise = "hello" 输入random stuff将返回“hello”,但如果我这样做 fn "" 我得到了非穷举模式错误。既然假定“”是一个空列表,[],它是否应该与我的第一个模式匹配并返回“empty”?Haskell中的字符串是一个字符列表。因此

我的程序有问题,我能够找出问题所在。我设法把它简化成这个更简单的问题。假设我有这个功能

fn:: String -> String
fn (x:xs)
    | null (x:xs) = "empty"
    | otherwise = "hello"
输入random stuff将返回“hello”,但如果我这样做

fn ""

我得到了非穷举模式错误。既然假定“”是一个空列表,
[]
,它是否应该与我的第一个模式匹配并返回
“empty”

Haskell中的
字符串是一个字符列表。因此,要匹配空的
字符串
,您需要匹配一个空列表(
[]
)。您的模式
(x:xs)
将只匹配至少有一个元素的列表或
字符串,因为它由一个元素(
x
)和其余元素(
xs
)组成,这些元素可以是空的,也可以是非空的

函数的工作版本如下所示:

fn :: String -> String
fn [] = "empty"
fn (x:xs) = "hello"
对于
fn”“

函数,这将返回
“empty”

fn:: String -> String
fn (x:xs)
    | null (x:xs) = "empty"
    | otherwise = "hello"
最好写为:

fn :: String -> String
fn x | null x    = "empty"
     | otherwise = "hello"

因为
null(x:xs)
肯定是错误的(总是错误的)

我更喜欢后者,因为它表明您只关心字符串类型


这是一个有点奇怪的函数。我还没有在实践中看到它。

非常感谢,我应该看到的!当然,空字符串literal
也可以在模式中使用,这个函数可以写成
fn”“=“empty”;fn=“你好”
fn :: String -> String
fn "" = "empty"
fn _  = "hello"