Memory allocation: Difference between revisions

Added Haskell implementation
m (→‎{{header|REXX}}: added comment about a non-error. -- ~~~~)
(Added Haskell implementation)
Line 389:
make(map[int]int)
make(chan int)</lang>
 
=={{header|Haskell}}==
 
You usually only need to do low-level memory management in Haskell when interfacing with code written in other languages (particularly C). At its most basic level, Haskell provides malloc()/free()-like operations in the IO monad.
 
<lang Haskell>import Foreign
 
bytealloc :: IO ()
bytealloc = do
a0 <- mallocBytes 100 -- Allocate 100 bytes
free a0 -- Free them again
allocaBytes 100 $ \a -> -- Allocate 100 bytes; automatically
-- freed when closure finishes
poke (a::Ptr Word32) 0</lang>
 
Slightly more sophisticated functions are available for automatically determining the amount of memory necessary to store a value of a specific type. The type is determined by type inference (in this example I use explicit manual type annotations, because poke is polymorphic).
 
<lang Haskell>import Foreign
 
typedalloc :: IO ()
typedalloc = do
w <- malloc
poke w (100 :: Word32)
free w
alloca $ \a -> poke a (100 :: Word32)</lang>
 
By the typing rules of Haskell, w must have the type 'Ptr Word32' (pointer to 32-bit word), which is how malloc knows how much memory to allocate.
 
=={{header|J}}==
Anonymous user