gpt4 book ai didi

Haskell 过滤掉循环排列

转载 作者:行者123 更新时间:2023-12-02 02:47:21 25 4
gpt4 key购买 nike

你有一个包含 N 个元素的列表
您只想打印不是同一列表中其他元素的循环排列的元素

要检查两个字符串是否是彼此的循环排列,我这样做,效果很好:

string1 = "abc"
string2 = "cab"
stringconc = string1 ++ string1
if string2 `isInfixOf` stringconc
then -- it's a circular permuation
else -- it's not

编辑:正如一条评论指出的那样,此测试仅适用于相同大小的字符串

回到实际用例:
checkClean :: [String] -> [String] -> IO String
checkClean [] list = return ""
checkClean (x:xs) list = do
let sequence = cleanInfix x list
if sequence /= "abortmath"
then putStr sequence
else return ()
checkClean xs list

清洁中缀:
cleanInfix :: String -> [String] -> String
cleanInfix seq [] = seq
cleanInfix seq (x:xs) = do
let seqconc = x ++ x
if seq `isInfixOf` seqconc && seq /= x
then "abortmath"
else cleanInfix seq xs

然而,这只是输出......什么都没有
通过一些研究,我发现 checkClean 中的序列总是“abortmath”
此外,我对这个“标志”abortmath 不太满意,因为如果有任何机会列表中的一个元素是“abortmath”,那么..

例如 :
如果我有一个由以下组成的列表:
NUUNNFFUF
FFUFNUUNN

我应该写
女巫

最佳答案

你可以用笔和一些纸创造的奇迹......

因此,如果有人对此感兴趣,这就是我解决它的方法,它可能优化得不好,但至少它有效(我只是想学习 haskell,所以现在已经足够了)

-- cleanInfix function
cleanInfix :: String -> [String] -> [String] -> [String]
cleanInfix sequence [] cleanlist = cleanlist
cleanInfix sequence (x:xs) cleanlist = do
-- this is where I check for the circular permuation
let sequenceconc = x ++ x
if sequence `isInfixOf` sequenceconc
then cleanInfix sequence xs (delete x cleanlist)
else cleanInfix sequence xs cleanlist


-- checkClean Function
checkClean :: [String] -> [String] -> [String] -> [String]
checkClean [] listesend cleanlist = cleanlist
checkClean (x:xs) listesend cleanlist = do
-- The first delete is to avoid checking if an element is the circular permuation of... itself, because it obviously is... in some way
let liste2 = cleanInfix x (delete x listesend) cleanlist
checkClean xs (delete x listesend) liste2


-- Clean function, first second and third are the command line argument don't worry about them
clean first second third = do
-- create of the result list by asking user for input

let printlist = checkClean result result result -- yes, it's the same list, three times
print printlist -- print the list

关于Haskell 过滤掉循环排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50193055/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com