我想获得以下字符串的一些轮换列表"我想今晚挣脱#34;。限制是旋转不能以单词" to"开头。或者"今晚"。所以轮换列表是["I want to break free today", "want to break free tonight I", "break free tonight I want to", "free tonight I want to break"]
。
我写了以下函数:
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的初学者。
答案 0 :(得分: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
函数会将单词列表转换回字符串。
答案 1 :(得分:1)
您需要multiprocessing.Queue()
中的intercalate :: [a] -> [[a]] -> [a]
功能。
来自hackage docs:
插入:: [a] - > [[a]] - > [α]插入xs xss相当于(concat(intersperse xs xss))。它 将列表xs插入xss中的列表之间并连接 结果
在Data.List
ghci