PFP Laboratory 10

From Marek Běhálek Wiki
Revision as of 07:31, 22 November 2022 by Beh01 (talk | contribs) (Created page with "== Monads == * In your prefered programming language, implement data type <syntaxhighlight lang="Haskell">bubbleSort :: Array Int Int -> Array Int Int</syntaxhighlight> <syn...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Monads

  • In your prefered programming language, implement data type
bubbleSort :: Array Int Int -> Array Int Int
ghci> elems $ bubbleSort $  listArray (0,5) [8,4,9,6,7,1] 
[1,4,6,7,8,9]
import Data.Array
import Data.Array.ST
import Control.Monad

bubbleSort :: Array Int Int -> Array Int Int
bubbleSort myArray = runSTArray  $ do
    stArray <- thaw myArray
    let end = (snd . bounds) myArray
    forM_ [1 .. end] $ \i -> do
        forM_ [0 .. (end - i)] $ \j -> do
            val <- readArray stArray j
            nextVal <- readArray stArray (j + 1)
            let outOfOrder = val > nextVal
            when outOfOrder $ do
                writeArray stArray j nextVal
                writeArray stArray (j + 1) val
    return stArray