How to create a two-dimensional array in Haskell?

I am trying to learn Haskell by creating a board game. I currently have a game [[Char]], and I'm trying to create another board from the same columns and lines that are filled with the character "a". How should I do it? Also can you explain how preservation of value and access will work?

+4
source share
1 answer

Instead of creating a new board of the same size but with different content, it may be useful to think of this operation as replacing the contents of an existing board. Of course, since Haskell is an immutable language, it is one and the same - the only way to change something is to create a new version of it, but it should help you understand that it is basically a mapping operation.

replaceWithA :: [[a]] -> [[Char]]
replaceWithA xss = map (map (const 'a')) xss
-- or, point-free:
replaceWithA = map (map (const 'a'))
-- or, as a list comprehension:
replaceValues xss = [['a' | x <- xs] | xs <- xss]

If you want to go deeper, you can get the compiler to write this code for you. A type class Functorgeneralizes mapto structures that are not simple lists:

class Functor f where
    fmap :: (a -> b) -> f a -> f b

In what sense is this generalization map? If you replace fwith [], you will see that it fmaphas the same signature as map:

fmap :: (a -> b) -> [a] -> [b]

In fact, this is how an instance is implemented [] Functor:

instance Functor [] where
    fmap = map

, GHC , Functor . newtype 2D- deriving Functor!

{-# LANGUAGE DeriveFunctor #-}
import Data.Functor

newtype TwoDimensional a = TwoDimensional { getTwoDimensional :: [[a]] } deriving Functor

fmap :

fmap :: (a -> b) -> TwoDimensional a -> TwoDimensional b

:

replaceWithA :: TwoDimensional a -> TwoDimensional Char
replaceWithA = ('a' <$)

, Haskell , Functor, , . , .

+3

Source: https://habr.com/ru/post/1673432/


All Articles