Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/haskell/8.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
学习Haskell:如何实现我自己版本的init函数_Haskell_Init - Fatal编程技术网

学习Haskell:如何实现我自己版本的init函数

学习Haskell:如何实现我自己版本的init函数,haskell,init,Haskell,Init,作为学习Haskell的一部分,我正在尝试实现与列表相关的各种函数的我自己的版本。现在我被困在init函数上。Haskell中的init函数返回列表中除最后一个元素以外的所有元素 以下是我迄今为止所做的工作 init' :: [Int] -> [Int] init' [] = error "This function cannot be applied to an empty list" init' [x] = [x] init' (x:xs) = x : init' xs 你的第二条规

作为学习Haskell的一部分,我正在尝试实现与列表相关的各种函数的我自己的版本。现在我被困在init函数上。Haskell中的init函数返回列表中除最后一个元素以外的所有元素

以下是我迄今为止所做的工作

init' :: [Int] -> [Int]
init' [] = error "This function cannot be applied to an empty list"
init' [x] = [x]
init' (x:xs) = x : init' xs

你的第二条规则应该是:

init' [x] = []
当一个列表只有一个元素时,它就是最后一个元素,因此没有最后一个元素的列表就是空列表

init' [x] = [x]
init' [x] = []

这是不对的。如果删除一个元素列表中的最后一个元素,则返回的不是同一个列表,而是一个空列表。

您的问题是基本情况。在这里:

init' [x] = [x]
init' [x] = [x]
init' [x] = []
您的意思是,当您进入一个包含一个元素的列表时,您希望返回相同的列表。这不是理想的结果。当列表中只有一个元素时,您希望返回一个空列表(除了单个项目的最后一个元素外,其他所有元素都是空列表)

另一方面,您可能应该将其声明为

init' :: [a] -> [a]

使用“a”作为类型将其概括为任何内容的列表,而不仅仅是int。这样,您就可以在任何类型的列表中调用init。例如,init的“abcde”会给你“abcd”

这是我的版本,试试这个

init' :: [a] -> [a]

init' []  = error("This is not right, empty list is not allowed here")
init' (x:[]) = [x]
init' (x:xs:[]) = [x]
init' (x:xs) = x: init' xs
safeInit=foldr((.)Just.maybe[]。(:)Nothing;-)