Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.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
String Haskell带例外的旋转字符串_String_Haskell - Fatal编程技术网

String Haskell带例外的旋转字符串

String Haskell带例外的旋转字符串,string,haskell,String,Haskell,我是Haskell的新手,我正在尝试将一个字符向右移,最后一个字符总是第一个,它将返回一个字符串 例如:shiftString“abcd”=“dabc”但是编译器不同意我的意见,有人能帮我解决这个问题吗 shiftString :: String -> String shiftString x = take (length x) $ iterate rot1 x where rot1 = drop 1 x ++ take 1 x 此外,我想在这之后检查两个字符串并返回Tr

我是Haskell的新手,我正在尝试将一个字符向右移,最后一个字符总是第一个,它将返回一个字符串

例如:
shiftString“abcd”=“dabc”
但是编译器不同意我的意见,有人能帮我解决这个问题吗

shiftString :: String -> String
shiftString x = take (length x) $ iterate rot1 x
        where rot1 = drop 1 x ++ take 1 x
此外,我想在这之后检查两个字符串并返回True,如果其中一个字符串是应用shiftString一次或多次的结果,我如何使用它来实现这一点?例如:

isShifted :: String -> String -> Bool

Haskell中的
String
只是
Char
s的列表-因此您可以使用简单的模式匹配来实现这一点:

shiftString':字符串->字符串
shiftString'(firstChar:restChars)=restChars++[firstChar]
移位字符串'[]=[]
现在,如果您尝试此操作,它将执行与您想要的相反的操作-但是有一个技巧:我们将字符串反转两次:

shiftString::String->String
换档串=倒档。移位字符串'。颠倒
这应该能奏效


修复您的:

我想您只需要
rot1
(它与我的
shiftString'
功能相同)以及上面的反向技巧

或者-要修复您的问题,请执行以下操作:

我猜您尝试了多次迭代到
rot1
,然后放弃了其余部分-这同样有效:

shiftS cs=head$drop(长度cs-1)$iterate rot1 cs
rot1 cs=放下1个cs++拿走1个cs
请注意,
iterate
为您提供了一个字符串列表(旋转次数越来越多)-我删除了第一个
n-1
(其中
n
=输入的长度),这再次为我提供了一个列表(您版本中的一个类型错误)并占据了该列表的开头,因为我只希望该列表中的第一个
String


对于您的
isShift
,您可以使用
rot1
重复使用
iterate
(无需关心顺序)-这一次从中获取
length cs
,然后检查您的其他输入是否是此列表的一个元素:

isShifted cs cs'=cs`elem`take(长度cs)(迭代循环1 cs')
例如:

Prelude>IsShift“abcd”“cdab”
真的
前奏曲>被切换为“abdc”“cdab”
假的

请注意,您不能只使用
迭代rot1 cs'
,而不使用take-请考虑一下,然后尝试所发生的事情;)(提示:当您的输入移位时,它会工作-但如果它们没有移位,您会遇到麻烦-为什么?

如何调用此函数以检查两个字符串是否是“移位字符串”的结果?我也更新了此项-我喜欢分步骤执行;)-我希望我不会破坏你太多的东西-这是家庭作业吗?以前是,但我弄错了,我正试图从我的错误中吸取教训(:
head(drop n foo)
写得更地道些
foo!!n
。是的,谢谢!可能还有很多我可以重写的东西-我的想法是让它尽可能接近我认为合理的原始代码
-- shiftString "abcd"   == "dabc"
-- shiftString "hello"  == "ohell"
-- shiftString "orange" == "eorang"

shiftString :: [a] -> [a]
shiftString lst = [ head (reverse lst)] ++ (init lst)


-- Test Cases
-- isShifted "abcdefg" "gabcdef"   == True
-- isShifted "hello" "ohell"       == True
-- isShifted "orange" "eorange"    == False



isShifted :: String -> String -> Bool
isShifted str1 str2                  
        | shiftString str1  == str2 = True
        | otherwise             = False