[Haskell-cafe] List operation question
Bryan Donlan
bd.haskell at uguu.us
Sun Feb 4 14:51:41 EST 2007
Eric Olander wrote:
> Hi,
> I'm still somewhat new to Haskell, so I'm wondering if there are
> better ways I could implement the following functions, especially shiftl:
>
> >> moves the first element to the end of the list
> shiftr :: [a] -> [a]
> shiftr [] = []
> shiftr (x:y) = y ++ [x]
>
> >> moves the last element to the head of the list
> shiftl :: [a] -> [a]
> shiftl [] = []
> shiftl x = [last x] ++ init x
If you use Data.Sequence (new in 6.6, I think), these can be O(1):
import qualified Data.Sequence as Seq
import Data.Sequence ( (<|), (|>), (:<), (:>) )
shiftr seq = go (Seq.viewl seq)
where
go (EmptyL) = Seq.empty
go (e :< remain) = remain |> e
shiftl seq = go (Seq.viewr seq)
where
go (EmptyR) = Seq.empty
go (remain :> e) = e <| remain
Decomposing by elements like this is a bit unwieldy, but using the
functions in Data.Traversable and Data.Foldable it shouldn't be too bad,
depending on what you're doing.
More information about the Haskell-Cafe
mailing list