[Haskell-beginners] exercises/examples for streams

Pascal Knodel pascal.knodel at mail.com
Sun Dec 14 22:52:24 UTC 2014


Hi Carl,

--------------------------------------- snip 
---------------------------------------
module BeginnerStreams where

-- 1. First try:

-- Contract:   Input lists are sorted.
--
-- Notes:
--
--   (!) Duplicate elements are allowed.
--   (!) Sort `Left` before `Right`.


sorts :: Ord a => [a] -> [a] -> [Either a a]
sorts (l : ls) (r : rs)

  |  l <= r     = Left l :           sorts      ls  (r : rs)

  |  otherwise  =          Right r : sorts (l : ls)      rs
  -- l >  r

sorts      []  (r : rs) =  Right r : sorts' Right rs
sorts (l : ls)      []  =  Left  l : sorts' Left  ls
sorts      []       []  =  []

sorts' e (i : is) =  e i : sorts' e is
sorts' _      []  =  []


-- The difficulty for me was: "Either".
-- I forgot about it while defining and
-- did wrong in defining the empty list
-- cases in my first definition:
--
--    sorts ls rs =  ls ++ rs
--
-- That isn't possible without constructor application,
-- because of the output type "[Either a a]". Is it?
--
-- Wish there would be GHCi in the exam.

-- Where else did I fail and didn't notice it?
-- What higher order functions would you use to define "sorts"?


-- 2. First try:

-- I'm not sure, what do you mean by 'value itself'?
-- Why is the second tuple (2,1)? Ah, I see, is it sth. like:
--
--  [1,3] is index 0 and becomes (0,1), (03)
--  [2,3]          1             (1,2), (1,3)
--  ...
--
-- And those sorted in ascending order by the sum of the components?
-- Is it possible to stream this computation without blocking?
-- Is the list-of-lists sorted?
--------------------------------------- snip 
---------------------------------------

The exercises from old exams that I have solved are at:
https://github.com/pascal-knodel/Programming-Paradigms-KIT-2014-2015/tree/master/3


Pascal




More information about the Beginners mailing list