1

I am trying to generate a list of lists with a specified dimension. the data type of this list looks something like this:

data A = X | Y | Z

so the list is of type [[A]]. (A is an instance of the Show type class so don't worry about that).

The user gives in a certain dimension (lets say width = 3 and height = 4), so the content could look like this:

[[X,Y,Z],
 [Y,Y,X],
 [Y,X,Z],
 [X,Z,Z]]

How can I generate a width X height 'matrix', the values aren't all that important at the moment.

thanks in advance.

EDIT: (for clarity reasons)

I just want to know how to generate a 'matrix' of type [[A]] with the width and height as user input. So width = number of elements in the inner list, height = number of lists in the outer list.

1 Answer 1

4

To generate a 3x4 nested list filled by a certain element, you can use:

data A = X | Y | Z deriving (Show)
generate width height = replicate height . replicate width

main = print $ generate 3 4 X

to get [[X,X,X],[X,X,X],[X,X,X],[X,X,X]].

Note that nested lists are not a great substitute for a 2D array in C/Java if the goal is to do frequent point updates. In those cases, use Data.Map or Data.Array.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.