Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

functional programming - Haskell: moving image on horizontal line

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...