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
List haskell中的列表递归_List_Haskell - Fatal编程技术网

List haskell中的列表递归

List haskell中的列表递归,list,haskell,List,Haskell,我有一张单子。我需要创建一个新列表,如下例所示: [3,3,1,3]至[3,3,3,1,1,3,3]。 谁能说出我的代码有什么问题吗 add xs = let adding (x : xs) as = if x == head(xs) && length(xs) >= 1 then adding xs (x : as) else adding xs (x

我有一张单子。我需要创建一个新列表,如下例所示:
[3,3,1,3]
[3,3,3,1,1,3,3]
。 谁能说出我的代码有什么问题吗

add xs
   = let
      adding (x : xs) as
         =
            if x == head(xs) && length(xs) >= 1
               then adding xs (x : as)
               else adding xs (x : x : as)
      adding _ as
         = as
   in
   adding xs []

ghci告诉我总是有空列表是
xs
,但我有
xs-length
控件

我不确定您最终要做什么,但我可以帮助您避免“空列表”问题

当列表
(x:xs)
中剩下一项时,
xs=[]
。(例如,如果
(x:xs)
仅包含项目
1
,则
x==1
xs==[]
)。在这种情况下,
head xs
会导致异常,因为没有为空列表定义
head

试着换线

if x == head(xs) && length(xs) >= 1

此更改后,当
xs=[]
时,
length(xs)>=1
计算结果为
False
。由于所有
p
False&&p==False
,Haskell跳过对其他表达式的求值(
x==head(xs)
),从而避免了异常情况。

尝试以下操作:

import Data.List
add xs = concat $ map (\(x:xs) -> x:x:xs) $ group xs

你能澄清一下你到底想让你的代码做什么吗?向列表中添加一个元素,如示例中所示。你的示例说
[3,3,1,3]
变成
[3,3,3,1,1,3,3]
。这是添加了不止一个元素。你的意思是说每个元素都应该被复制,从而产生一个长度是原始长度两倍的列表吗?你的例子也没有说明这一点。你是否打算结果应该是
[3,3,3,3,1,1,3,3]
?那么我仍然不知道你想做什么。请指定每个列表的输出内容:
[1,2,3]
[2,2,2]
[]
[1]
@Neil:我很确定他想要
concatMap(\(x:xs)->x:xs))。组
。这看起来更易于阅读:
添加xss=concat[x:x:xs|(x:xs)完整的代码&没有对OP的尝试进行推导、解释或分析。-1
import Data.List
add xs = concat $ map (\(x:xs) -> x:x:xs) $ group xs