Haskell: moving image on horizontal line

不问归期 提交于 2019-12-13 10:13:20

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!