Difference between revisions of "FP Laboratory 10"

From Marek Běhálek Wiki
Jump to navigation Jump to search
Line 8: Line 8:
 
isEmpty :: Stack a ->Bool
 
isEmpty :: Stack a ->Bool
 
</syntaxhighlight>
 
</syntaxhighlight>
 +
 +
<div class="mw-collapsible mw-collapsed" data-collapsetext="Hide solution" data-expandtext="Show solution">
 +
<syntaxhighlight lang="Haskell">
 +
</syntaxhighlight>
 +
</div>
 +
<div style="clear:both"></div>
 +
 
* Create an abstract data type <code>Queue</code> with following functions:
 
* Create an abstract data type <code>Queue</code> with following functions:
 
<syntaxhighlight lang="Haskell">
 
<syntaxhighlight lang="Haskell">
Line 14: Line 21:
 
remQ :: Queue q -> (a, Queue a)
 
remQ :: Queue q -> (a, Queue a)
 
</syntaxhighlight>
 
</syntaxhighlight>
 +
 +
<div class="mw-collapsible mw-collapsed" data-collapsetext="Hide solution" data-expandtext="Show solution">
 +
<syntaxhighlight lang="Haskell">
 +
module Queue(Queue, emptyQ, isEmptyQ, addQ, remQ) where
 +
    data Queue a = Qu [a]
 +
 +
    emptyQ :: Queue a
 +
    emptyQ = Qu []
 +
   
 +
    isEmptyQ :: Queue a -> Bool
 +
    isEmptyQ (Qu q) = null q
 +
   
 +
    addQ :: a -> Queue a -> Queue a
 +
    addQ x (Qu xs) = Qu (xs++[x])
 +
   
 +
    remQ :: Queue a -> (a,Queue a)
 +
    remQ q@(Qu xs) | not (isEmptyQ q) = (head xs, Qu (tail xs))
 +
                  | otherwise        = error "remQ"
 +
</syntaxhighlight>
 +
</div>
 +
<div style="clear:both"></div>

Revision as of 10:05, 24 September 2020

Abstract data types

  • Create an abstract data type Stack with following functions:
push :: a -> Stack a -> Stack a
pop :: Stack a -> Stack a
top :: Stack a -> a
isEmpty :: Stack a ->Bool
  • Create an abstract data type Queue with following functions:
isEmpty :: Queue a -> Bool
addQ :: a -> Queue a -> Queue a
remQ :: Queue q -> (a, Queue a)
module Queue(Queue, emptyQ, isEmptyQ, addQ, remQ) where
    data Queue a = Qu [a]

    emptyQ :: Queue a
    emptyQ = Qu []
    
    isEmptyQ :: Queue a -> Bool
    isEmptyQ (Qu q) = null q
    
    addQ :: a -> Queue a -> Queue a
    addQ x (Qu xs) = Qu (xs++[x])
    
    remQ :: Queue a -> (a,Queue a)
    remQ q@(Qu xs) | not (isEmptyQ q) = (head xs, Qu (tail xs))
                   | otherwise        = error "remQ"