问题
Im new to Haskell and am working with images represented as type Img = [String].
I want to move the image either left or right by 1 or more rows with a wrap.
i've manged to move the images up or down, code below:
moveVer :: Int -> Img -> Img
moveVer n xs = take len $ drop (mod n len) $ cycle xs
where len = length xs
img 1 = XXXXXX OUTPUT = (moveVer (3)(img 1)) = XX
XX XX
XX XXXXXX
XX XXXXXX
XXXXXX XX
Now i'm trying to do the same thing but move the image horizontally (left or right).
function to defined moveHor :: Int -> Img -> Img
回答1:
The fundamental algorithm is the same as your vertical shift function, since String is also a list of characters, [Char].
You can generalize your algorithm to a move function since the code for moveVer really only requires a list and has no dependency on Img:
move :: Int -> [a] -> [a]
move n xs = take len $ drop (mod n len) $ cycle xs
where len = length xs
Now you can rewrite your moveVer function in terms of move:
moveVer :: Int -> Img -> Img
moveVer = move
And since a string is just a List of characters, you can map over the list of strings and use the move function to do your horizontal movement.
moveHor :: Int -> Img -> Img
moveHor n = map $ move n
来源:https://stackoverflow.com/questions/36499786/haskell-moving-image-on-horizontal-line