简体   繁体   English

Haskell 字符串旋转 Function

[英]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 ,它接受一个Strings和一个Integeri ,然后在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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM