0

I've created a:

 newType Board = Board (Array (Int, Int) Life)

, where

 data Life = Alive|Dead

Im trying to make a function to save the board to a String by pattern matching:

showBoard:: Config -> String
showBoard Board(array ((0, 0), (w, h)) [(a:as)]) = *code*

But this only gives me "Parse error in pattern: array". I cant see what's wrong?

3
  • Array is a type constructor; what does its data constructor look like? Commented Nov 6, 2016 at 14:57
  • Im using the Data.Array library Commented Nov 6, 2016 at 15:06
  • array is a function that returns an Array value, but it is not a data constructor. Data.Array does not appear to export any data constructors, so you cannot do pattern matching on those values. Commented Nov 6, 2016 at 15:40

1 Answer 1

4

You can only pattern-match on data constructors. array is not a data constructor; it is a regular function that internal uses the Array data constructor(s) to create and return an Array value. The internal details of an Array are not exposed, preventing you from pattern-matching on them.

Instead, you need use the functions provided for looking at an Array value. These can be composed with a function that does take arguments you can pattern match on.

-- bounds :: Array i e -> (i, i)
-- elems :: Array i e -> [e]
showConfig :: Board -> String
showConfig (Board arr) = showConfig' (bounds arr) (elems arr)
  where showConfig' :: ((Int,Int),(Int,Int)) -> [Life] -> String
        showConfig' ((0,0),(w,h)) (a:as) = ...

If you modify your Board type to

newtype Board = Board { getArray :: Array (Int, Int) Life }

you can rewrite showConfig in an applicative style:

showConfig = (showConfig' <$> boards <*> elems) . getArray
  where showConfig' ((0,0),(w,h)) (a:as) = ...
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.