[英]Haskell String Rotation Function
I need to write a Haskell function that that takes a String
, s
, and an Integer
, i
, then performs i
rotations right on s
.我需要编写一个 Haskell function ,它接受一个
String
, s
和一个Integer
, i
,然后在s
上执行i
旋转。
rotate:: String -> Integer -> String
I have been successful in getting it to work with String -> Int -> String
but I am being asked to do it with Integer
我已经成功地让它与
String -> Int -> String
一起工作,但我被要求用Integer
This is what I have implemented with Int
:这是我用
Int
实现的:
rotate str n = take (length str) $ drop (negate n `mod` length str) $ cycle str
The problem is that drop:: Int -> [a] -> [a]
takes an Int
as type parameter.问题是
drop:: Int -> [a] -> [a]
将Int
作为类型参数。 Furthermore length:: Foldable f => fa -> Int
for example produces an Int
.此外
length:: Foldable f => fa -> Int
例如产生一个Int
。 So that will not work.所以那是行不通的。
There are however generic variants that work with Integral
types or Num
types, for example genericDrop:: Integral i => i -> [a] -> [a]
and genericLength:: Num i => [a] -> i
:然而,有一些泛型变体适用于
Integral
类型或Num
类型,例如genericDrop:: Integral i => i -> [a] -> [a]
和genericLength:: Num i => [a] -> i
:
import Data.List(genericDrop, genericLength, genericTake)
rotate :: Integral i => [a] -> i -> [a]
rotate str n = genericTake l (genericDrop ((-n) `mod` l) (cycle str))
where l = genericLength str
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.