1

I cannot understand haskell arrays.

For example I want to create and store an array in variable bsd but what goes in .... if I want an array of size eg 10 and of type Bool.

bsd :: Array Int Bool --is this correct?
bsd = .... --what comes here?

Please help me understand...

and what if I want to change a value in bsd at e.g. index 5 what is the syntax

and how can i access a index in bsd ??

please help

1
  • 1
    An Array is a pure value. You can't change it. There are operations for creating new arrays representing modifications of old ones, but those are too slow for any non-small arrays. If your arrays really have just ten or so elements, then that's likely fine, but otherwise you might want to use mutable arrays or pure sequences. Commented Sep 25, 2017 at 4:09

1 Answer 1

2

Using https://hackage.haskell.org/package/array-0.5.2.0/docs/Data-Array-IArray.html

This constructs an array of bools from a list. There are tons of other options and functions to use as well

import Data.Array.IArray
let bsd = listArray (0, 3) [False, True, True, False] :: Array Int Bool
elems bsd -- [False,True,True,False]
bsd -- array (0,3) [(0,False),(1,True),(2,True),(3,False)]
bsd ! 0 -- Get element at index 0, which is False
-- Create new array with element 0 changed to True.
let bsd2 = bsd // [(0, True)]
bsd2 -- array (0,3) [(0,True),(1,True),(2,True),(3,False)]
Sign up to request clarification or add additional context in comments.

4 Comments

how can i say get the size of bsd? and how can i assign to say index 2 ?
@Jhoy bsd // [(2,False)] to assign at index 2 ?
For the size you could do indices bsd which returns the list of indices and then take the length of this list (maybe there's a better way, I don't know).
bounds bsd gives you min+max index, so you can get length from that. Also MArray or Data.Array.ST are better for scenarios involving lots of mutation.

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.