Difference between revisions of "FP Laboratory 10"

From Marek Běhálek Wiki
Jump to navigation Jump to search
Line 1: Line 1:
 +
<translate>
 
== Abstract data types ==
 
== Abstract data types ==
 +
</translate>
 +
 
<div style="float: right"> [[File:Video logo.png|80px|link=https://youtu.be/Stx4YcQbZzg]]</div>  
 
<div style="float: right"> [[File:Video logo.png|80px|link=https://youtu.be/Stx4YcQbZzg]]</div>  
 +
 +
<translate>
 
* Create an implementation of the abstract data type [https://en.wikipedia.org/wiki/Stack_(abstract_data_type) <code>Stack</code>] with following functions:
 
* Create an implementation of the abstract data type [https://en.wikipedia.org/wiki/Stack_(abstract_data_type) <code>Stack</code>] with following functions:
 +
</translate>
  
 
<syntaxhighlight lang="Haskell">
 
<syntaxhighlight lang="Haskell">
Line 34: Line 40:
 
<div style="clear:both"></div>
 
<div style="clear:both"></div>
  
 +
<translate>
 
* Create an implementation of the abstract data type [https://en.wikipedia.org/wiki/Queue_(abstract_data_type) <code>Queue</code>] with following functions:
 
* Create an implementation of the abstract data type [https://en.wikipedia.org/wiki/Queue_(abstract_data_type) <code>Queue</code>] with following functions:
 +
</translate>
 +
 
<syntaxhighlight lang="Haskell">
 
<syntaxhighlight lang="Haskell">
 
isEmpty :: Queue a -> Bool
 
isEmpty :: Queue a -> Bool

Revision as of 08:24, 21 October 2021

Abstract data types

Video logo.png
  • Create an implementation of the 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
module Stack(Stack, emptyS, push, pop, top, isEmpty) where
  data Stack a = Stack [a] deriving Show

  emptyS :: Stack a
  emptyS = Stack []

  push :: a -> Stack a -> Stack a
  push x (Stack y) = Stack (x:y)
  
  pop :: Stack a -> Stack a
  pop (Stack (_:xs)) = Stack xs

  top :: Stack a -> a
  top (Stack (x:_)) = x

  isEmpty :: Stack a ->Bool
  isEmpty (Stack []) = True
  isEmpty _ = False
  • Create an implementation of the 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] deriving Show

    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"