root/hiersort/core/S.hs

Revision 1, 2.4 kB (checked in by thesz, 2 years ago)

Initial commit

Line 
1 -- | S.hs
2 --
3 -- This module contains core definitions used by the rest of system.
4 -- Here we have the famous infinite list (S a) and some primitives.
5 --
6 -- Copytight (C) 2007, 2008 Serguey Zefirov
7 --
8 -- This program is free software; you can redistribute it and/or modify
9 -- it under the terms of the GNU General Public License as published by
10 -- the Free Software Foundation; either version 3, or (at your option)
11 -- any later version.
12 -- See file COPYING or visit http://www.gnu.org/licenses for details.
13
14 -- {-# INLINE #-} anything here didn't proved worthwhile.
15 --
16 -- I think that all parallelisation calls should be placed here.
17 -- And they are, indeed.
18
19 module S where
20
21 import Data.List
22 import Control.Parallel
23
24 -- The Infinite List, as it is. We call it stream for short.
25 data S a = S a (S a)
26
27 -- Usual conversion to list.
28 toList (S a s) = a:toList s
29
30 -- Safe instance of show - does not display too much information.
31 instance Show a => Show (S a) where
32         show s = (++"...") $ tail $ init $ show $ take 20 $ toList s
33
34 -- Constant value stream.
35 constS c = let s = S c s in s
36
37 -- And delaying a stream with given value.
38 delayS x s = S x s
39
40 -- Make a stream from starting list and default value.
41 fromListS c [] = constS c
42 fromListS c (x:xs) = delayS x $ fromListS c xs
43
44 -- Make a series of delayS'.
45 prependS [] = id
46 prependS (x:xs) = delayS x . prependS xs
47
48 -- Cycle a list and make it a stream.
49 loopPrefixS l = let r = prependS l r in r
50
51 -- mapping.
52 mapS f ~(S x xs) = S (f x) $ mapS f xs
53
54 -- Unzipper. Used to fan out a bus (stream of tuples) into tuple of streams.
55 unzipS s = fi `pseq` (se `par` fi,se)
56         where
57                 fi = mapS fst s
58                 se = mapS snd s
59
60 unzipS3 abcs = (mapS (\(a,b,c) -> a) abcs,mapS (\(a,b,c) -> b) abcs, mapS (\(a,b,c) -> c) abcs)
61
62 -- Usual zipper. An inverse for unzipS.
63 zipS ~(S a as) ~(S b bs) = S (a,b) $ zipS as bs
64
65 -- General zipper.
66 zipWithS f ~(S a as) ~(S b bs) = S (f a b) $ zipWithS f as bs
67
68 -- Thread state through state changer function (Mealy state machine).
69 loopS :: st -> (st -> i -> (st,o)) -> S i -> S o
70 loopS s0 f is = xs
71         where
72                 (ss,xs) = unzipS $ mapS (uncurry f') $ zipS (delayS s0 ss) is
73                 f' st i = (st `par` (st `pseq` f st i))
74
75 -- Fairly esotheric.
76 -- Convert list of streams to stream of lists.
77 -- It ain't used here, but can be useful.
78 listSToSList :: [S a] -> S [a]
79 listSToSList listS =
80           fromListS
81                 (error "listSToSList: cannot be!") -- default value for fromListS
82         $ transpose
83         $ map toList listS
Note: See TracBrowser for help on using the browser.