Difference between revisions of "PFP Laboratory 10"

From Marek Běhálek Wiki
Jump to navigation Jump to search
(Created page with "== Monads == * In your prefered programming language, implement data type <syntaxhighlight lang="Haskell">bubbleSort :: Array Int Int -> Array Int Int</syntaxhighlight> <syn...")
 
 
Line 1: Line 1:
 
== Monads ==  
 
== Monads ==  
* In your prefered programming language, implement data type  
+
* In your prefered programming language, implement data type representing <code>Maybe</code>.
<syntaxhighlight lang="Haskell">bubbleSort :: Array Int Int -> Array Int Int</syntaxhighlight>
+
* Implement functions '''bind''' and '''return''' as it is defined for monads.
<syntaxhighlight lang="Haskell" class="myDark">
+
* Using implemented opertions, implement functions '''apply''' and '''fmap''' as it is define for <code>Applicative</code> and <code>Functor</code>.
ghci> elems $ bubbleSort $  listArray (0,5) [8,4,9,6,7,1]
 
[1,4,6,7,8,9]
 
</syntaxhighlight>
 
 
 
<div class="mw-collapsible mw-collapsed" data-collapsetext="Hide solution" data-expandtext="Show solution">
 
<syntaxhighlight lang="Haskell">
 
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
 
</syntaxhighlight>
 
</div>
 
<div style="clear:both"></div>
 

Latest revision as of 07:55, 22 November 2022

Monads

  • In your prefered programming language, implement data type representing Maybe.
  • Implement functions bind and return as it is defined for monads.
  • Using implemented opertions, implement functions apply and fmap as it is define for Applicative and Functor.