2017-03-12 45 views
1

我想获得以下字符串“我想今晚挣脱”的一些旋转列表。约束条件是轮换不能以“to”或“tonight”开头。所以旋转列表是["I want to break free today", "want to break free tonight I", "break free tonight I want to", "free tonight I want to break"]Haskell中的列表旋转

我写以下功能:

rotate :: [l] -> [l] 
rotate [] = [] 
rotate (x:xs) = (x:xs) ++ head(x:xs) 

rotate1 :: [a] -> [[a]] 
rotate1 xs = take (length xs) (iterate rotate xs) 

main = do 
print $ rotate1(words("I want to break free tonight")) 

运行该代码,我所获得的所有可能的旋转,但他们形成具有像["want", "I", "to", "break", "free", "tonight"],其是从字符串"want I to break free tonight"不同元素列表的列表。另外,我想看看如何放弃以"to""tonight"这个词开头的旋转。我试图为第二部分使用过滤器功能,但我没有设法解决问题。任何帮助/提示表示赞赏。我注意到我是Haskell的初学者。

回答

1

您想要功能intercalate :: [a] -> [[a]] -> [a]Data.List

从hackage文档:

插::并[a] - > [[α]] - >并[a]

地嵌入XS XSS相当于(CONCAT(间置XS XSS) )。它 在xss列表之间插入列表xs并连接 结果。

ghci

> import Data.List 
> intercalate " " ["want", "I", "to", "break", "free", "tonight"] 
> "want I to break free tonight" 
+2

或者你可以使用'unwords'这是在前奏。 –

+0

感谢您的建议。我知道函数过滤和插入或unwords,但我的问题是,我必须将它们应用到列表的列表。由于在Haskell中没有类似的指令,我不知道如何通过列表并将函数应用到每个元素。举例来说,我不能用unwords([ “I”, “希望”, “来”, “破发”, “自由”, “今夜”],[ “希望”, “我”, “来”,“休息“,”自由“,”今晚“]])获得名单[”我想今晚休息“,”希望我今晚休息“]。 – Bob

3

运行这段代码...

的代码不会运行。它有类型错误。

首先,让我们来修正格式,以便更容易阅读,删除多余的括号

rotate :: [l] -> [l] 
rotate [] = [] 
rotate (x:xs) = (x:xs) ++ head (x:xs) 

rotate1 :: [a] -> [[a]] 
rotate1 xs = take (length xs) (iterate rotate xs) 

main = print $ rotate1 (words "I want to break free tonight") 

这是奇怪的:

rotate (x:xs) = (x:xs) ++ head (x:xs) 

首先,x:xs是整个列表,并且x是该列表的头部。例如,rotate [1, 2, 3]变为:

rotate [1, 2, 3] = let x = 1 
         xs = [2, 3] 
        in (x:xs) ++ head (x:xs) 

rotate [1, 2, 3] = (1:[2, 3]) ++ head (1:[2, 3]) 
rotate [1, 2, 3] = [1, 2, 3] ++ head [1, 2, 3] 
rotate [1, 2, 3] = [1, 2, 3] ++ 1 
        -- type error 

++需要双方的列表。你可能想在这里是什么:

rotate (x:xs) = xs ++ [x] 

这给了我们:

rotate [1, 2, 3] = let x = 1 
         xs = [2, 3] 
        in xs ++ [x] 
rotate [1, 2, 3] = [2, 3] ++ [1] 
rotate [1, 2, 3] = [2, 3, 1] 

这是一样的:

rotate x = tail x ++ [head x] 

您的问题休息...过滤器应该直截了当因为有一个filter函数可以完全满足你的需求,而unwords函数可以将单词列表转换回字符串。