├── old ├── paper.odt ├── alternate_timelines_mclean.pdf ├── make-paper.sh └── paper.md ├── .gitignore ├── src └── Sound │ └── Tidal2 │ ├── Value.hs │ ├── Time.hs │ ├── Pattern.hs │ ├── Types.hs │ ├── Signal.hs │ ├── Parse.hs │ └── Sequence.hs ├── test └── Test.hs ├── remake.cabal └── LICENSE /old/paper.odt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yaxu/remake/HEAD/old/paper.odt -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *~ 2 | *.hi 3 | *.dyn_hi 4 | *.dyn_o 5 | dist/ 6 | dist-newstyle/ 7 | *.swp 8 | -------------------------------------------------------------------------------- /old/alternate_timelines_mclean.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yaxu/remake/HEAD/old/alternate_timelines_mclean.pdf -------------------------------------------------------------------------------- /old/make-paper.sh: -------------------------------------------------------------------------------- 1 | pandoc paper.md --citeproc --number-sections --bibliography /home/alex/Dropbox/cite/Alpaca.json --bibliography /home/alex/Dropbox/cite/My\ Library.json -o paper.docx 2 | -------------------------------------------------------------------------------- /src/Sound/Tidal2/Value.hs: -------------------------------------------------------------------------------- 1 | {-# LANGUAGE DeriveFunctor #-} 2 | 3 | -- (c) Alex McLean 2022 4 | -- Shared under the terms of the GNU Public License v. 3.0 5 | 6 | module Sound.Tidal2.Value where 7 | 8 | import Data.Ratio 9 | 10 | data Value = S String 11 | | F Double 12 | | R Rational 13 | deriving (Show) 14 | -------------------------------------------------------------------------------- /src/Sound/Tidal2/Time.hs: -------------------------------------------------------------------------------- 1 | module Sound.Tidal2.Time where 2 | 3 | -- (c) Alex McLean 2022 4 | -- Shared under the terms of the GNU Public License v. 3.0 5 | 6 | -- | Timespan (called an arc in tidal v1) 7 | data Span = Span {begin :: Rational, end :: Rational} 8 | deriving (Show) 9 | 10 | -- | Intersection of two timespans 11 | sect :: Span -> Span -> Span 12 | sect (Span b e) (Span b' e') = Span (max b b') (min e e') 13 | 14 | -- | Intersection of two timespans, returns Nothing if they don't intersect 15 | maybeSect :: Span -> Span -> Maybe Span 16 | maybeSect a b = check $ sect a b 17 | where check :: Span -> Maybe Span 18 | check (Span a b) | b <= a = Nothing 19 | | otherwise = Just (Span a b) 20 | 21 | 22 | -- | The start of the cycle that a given time value is in 23 | sam :: Rational -> Rational 24 | sam s = toRational $ floor s 25 | 26 | -- | The start of the next cycle 27 | nextSam :: Rational -> Rational 28 | nextSam s = sam s + 1 29 | 30 | -- | Splits a timespan at cycle boundaries 31 | splitSpans :: Span -> [Span] 32 | splitSpans (Span b e) | e <= b = [] 33 | | sam b == sam e = [Span b e] 34 | | otherwise 35 | = (Span b (nextSam b)):(splitSpans (Span (nextSam b) e)) 36 | -------------------------------------------------------------------------------- /test/Test.hs: -------------------------------------------------------------------------------- 1 | import Control.Applicative hiding (some) 2 | import Data.Void 3 | import Test.Hspec 4 | import Test.Hspec.Megaparsec 5 | import Text.Megaparsec 6 | import Text.Megaparsec.Char 7 | 8 | import Sound.Tidal2.Pattern 9 | import Sound.Tidal2.Types 10 | import Sound.Tidal2.Parse 11 | 12 | main :: IO () 13 | main = hspec $ do 14 | describe "Integers" $ do 15 | it "can parse a pure number as a pattern" $ 16 | parse (pClosed (T_Pattern T_Int)) "" "(pure 3)" `shouldParse` (Tk_App Tk_pure (Tk_Int 3)) 17 | it "can parse addition" $ 18 | parse (pClosed (T_Int)) "" "(4 + 3)" `shouldParse` (Tk_Op (Just $ Tk_Int 4) Tk_plus (Just $ Tk_Int 3)) 19 | it "can parse subtraction" $ 20 | parse (pClosed (T_Int)) "" "(4 - 3)" `shouldParse` (Tk_Op (Just $ Tk_Int 4) Tk_subtract (Just $ Tk_Int 3)) 21 | it "can parse multiplication" $ 22 | parse (pClosed (T_Int)) "" "(4 * 3)" `shouldParse` (Tk_Op (Just $ Tk_Int 4) Tk_multiply (Just $ Tk_Int 3)) 23 | it "can parse division" $ 24 | parse (pClosed (T_Int)) "" "(4 / 3)" `shouldParse` (Tk_Op (Just $ Tk_Int 4) Tk_divide (Just $ Tk_Int 3)) 25 | it "can parse arithmetic in parens" $ 26 | parse (pClosed (T_Int)) "" "(((4 / 3) * 2) + (1+0))" `shouldParse` (Tk_Op (Just (Tk_Op (Just (Tk_Op (Just (Tk_Int 4)) Tk_divide (Just (Tk_Int 3)))) Tk_multiply (Just (Tk_Int 2)))) Tk_plus (Just (Tk_Op (Just (Tk_Int 1)) Tk_plus (Just (Tk_Int 0))))) 27 | 28 | 29 | -------------------------------------------------------------------------------- /remake.cabal: -------------------------------------------------------------------------------- 1 | cabal-version: 2.4 2 | name: tidal-remake 3 | version: 0.1.0 4 | 5 | synopsis: DSL for live coding pattern and rhythm 6 | 7 | -- A longer description of the package. 8 | -- description: 9 | 10 | -- A URL where users can report bugs. 11 | -- bug-reports: 12 | 13 | -- The license under which the package is released. 14 | -- license: 15 | author: Alex McLean 16 | maintainer: Alex McLean 17 | 18 | -- A copyright notice. 19 | -- copyright: 20 | category: Sound 21 | license-file: LICENSE 22 | -- extra-source-files: CHANGELOG.md 23 | 24 | library remake 25 | -- Modules included in this executable, other than Main. 26 | -- other-modules: 27 | 28 | -- LANGUAGE extensions used by modules in this package. 29 | -- other-extensions: 30 | build-depends: base, 31 | containers, 32 | mtl, 33 | megaparsec 34 | hs-source-dirs: src 35 | ghc-options: -Wall 36 | default-language: Haskell2010 37 | Exposed-modules: Sound.Tidal2.Pattern 38 | Sound.Tidal2.Parse 39 | Sound.Tidal2.Types 40 | test-suite tests 41 | type: exitcode-stdio-1.0 42 | default-language: Haskell2010 43 | main-is: Test.hs 44 | hs-source-dirs: 45 | test 46 | ghc-options: -Wall 47 | -- other-modules: Sound.Tidal2.PatternTest 48 | -- Sound.Tidal2.ParseTest 49 | -- Sound.Tidal2.TypesTest 50 | build-depends: 51 | base 52 | , hspec 53 | , hspec-megaparsec 54 | , containers 55 | , megaparsec 56 | , remake 57 | -------------------------------------------------------------------------------- /src/Sound/Tidal2/Pattern.hs: -------------------------------------------------------------------------------- 1 | -- (c) Alex McLean and contributors 2022 2 | -- Shared under the terms of the GNU Public License v3.0 3 | 4 | module Sound.Tidal2.Pattern where 5 | 6 | import Data.Ratio 7 | 8 | class Functor f => Pattern f where 9 | slowcat :: [f a] -> f a 10 | fastcat :: [f a] -> f a 11 | fastcat pats = _fast (toRational $ length pats) $ slowcat pats 12 | _fast :: Rational -> f a -> f a 13 | _early :: Rational -> f a -> f a 14 | silence :: f a 15 | atom :: a -> f a 16 | stack :: [f a] -> f a 17 | _patternify :: (a -> b -> f c) -> (f a -> b -> f c) 18 | -- rev :: f a -> f a 19 | -- ply :: f Rational -> f a -> f a 20 | -- _ply :: Rational ->f a-> f a 21 | -- euclid :: f Int -> f Int -> f String -> f String 22 | -- _euclid :: Int -> Int -> f a-> f a 23 | -- timeCat :: [(Rational, f a)] -> f a 24 | -- timecat :: [(Rational, f a)] -> f a 25 | -- fromList :: [a] -> f a 26 | -- fastFromList :: [a] -> f a 27 | -- fromMaybes :: [Maybe a] -> f a 28 | -- run :: (Enum a, Num a) => f a -> f a 29 | -- _run :: (Enum a, Num a) => a -> f a 30 | -- scan :: (Enum a, Num a) => f a -> f a 31 | -- _scan :: (Enum a, Num a) => a -> f a 32 | -- every :: f Int -> (f b -> f b) -> f b -> f b 33 | -- _every :: Int -> (f a -> f a) -> f a -> f a 34 | -- listToPat :: [a] -> f a 35 | -- density :: f Rational -> f a-> f a 36 | -- iter :: f Int -> f a -> f a 37 | -- iter' :: f Int -> f a -> f a 38 | -- _iter :: Int -> f a -> f a 39 | -- _iter' :: Int -> f a -> f a 40 | -- (<~) :: f Rational -> f a -> f a 41 | 42 | _slow :: Pattern p => Rational -> p x -> p x 43 | _slow t = _fast (1/t) 44 | 45 | slow :: Pattern p => p Rational -> p x -> p x 46 | slow = _patternify _slow 47 | 48 | fastappend :: Pattern p => p x -> p x -> p x 49 | fastappend a b = fastcat [a,b] 50 | 51 | slowappend :: Pattern p => p x -> p x -> p x 52 | slowappend a b = slowcat [a,b] 53 | 54 | append :: Pattern p => p x -> p x -> p x 55 | append = slowappend 56 | 57 | early :: Pattern p => p Rational -> p x -> p x 58 | early = _patternify _early 59 | 60 | (<~) :: Pattern p => p Rational -> p x -> p x 61 | (<~) = early 62 | 63 | _late :: Pattern p => Rational -> p x -> p x 64 | _late t = _early (0-t) 65 | 66 | late :: Pattern p => p Rational -> p x -> p x 67 | late = _patternify _late 68 | 69 | (~>) :: Pattern p => p Rational -> p x -> p x 70 | (~>) = late 71 | 72 | -- | Converts from a range from 0 to 1, to a range from -1 to 1 73 | toBipolar :: (Pattern p, Fractional x) => p x -> p x 74 | toBipolar pat = fmap (\v -> (v*2)-1) pat 75 | 76 | -- | Converts from a range from -1 to 1, to a range from 0 to 1 77 | fromBipolar :: (Pattern p, Fractional x) => p x -> p x 78 | fromBipolar pat = fmap (\v -> (v+1)/2) pat 79 | 80 | -------------------------------------------------------------------------------- /src/Sound/Tidal2/Types.hs: -------------------------------------------------------------------------------- 1 | module Sound.Tidal2.Types where 2 | 3 | import Data.List (intersectBy, nub, (\\), intercalate) 4 | import Data.Maybe (isJust) 5 | import Sound.Tidal2.Pattern 6 | 7 | -- ************************************************************ -- 8 | -- Types of types 9 | 10 | data Type = 11 | T_F Type Type 12 | | T_String 13 | | T_Float 14 | | T_Int 15 | | T_Rational 16 | | T_Bool 17 | | T_Map 18 | | T_Pattern Type 19 | | T_Constraint Int 20 | | T_List Type 21 | | T_SimpleList Type 22 | deriving Eq 23 | 24 | data Constraint = 25 | C_OneOf [Type] 26 | | C_WildCard 27 | deriving Eq 28 | 29 | instance Show Type where 30 | show (T_F a b) = "(" ++ show a ++ " -> " ++ show b ++ ")" 31 | show T_String = "s" 32 | show T_Float = "f" 33 | show T_Int = "i" 34 | show T_Rational = "r" 35 | show T_Bool = "#" 36 | show T_Map = "map" 37 | show (T_Pattern t) = "p [" ++ (show t) ++ "]" 38 | show (T_Constraint n) = "constraint#" ++ (show n) 39 | show (T_List t) = "list [" ++ (show t) ++ "]" 40 | show (T_SimpleList t) = "simplelist [" ++ (show t) ++ "]" 41 | 42 | instance Show Constraint where 43 | show (C_OneOf ts) = "?" ++ show ts 44 | show C_WildCard = "*" 45 | 46 | -- Type signature 47 | data Sig = Sig {constraints :: [Constraint], 48 | is :: Type 49 | } 50 | deriving Eq 51 | 52 | instance Show Sig where 53 | show s = ps ++ (show $ is s) 54 | where ps | constraints s == [] = "" 55 | | otherwise = show (constraints s) ++ " => " 56 | 57 | data Code = 58 | Cd_Int Int | Cd_Rational Rational | Cd_String String | Cd_Float Float | Cd_Bool Bool | 59 | Cd_App Code Code | 60 | Cd_Op (Maybe Code) Code (Maybe Code) | 61 | Cd_R R | 62 | Cd_every | Cd_fast | 63 | Cd_plus | 64 | Cd_multiply | 65 | Cd_divide | 66 | Cd_subtract | 67 | Cd_rev | 68 | Cd_hash | 69 | Cd_dollar | 70 | Cd_pure | 71 | Cd_name String 72 | deriving (Show, Eq) 73 | 74 | data R = R_Atom String 75 | | R_Silence 76 | | R_Subsequence [R] 77 | | R_StackCycles [R] 78 | | R_StackStep [R] 79 | | R_StackSteps [R] 80 | | R_Duration Code R 81 | | R_Patterning Code R 82 | deriving (Show, Eq) 83 | 84 | data Fix = Prefix | Infix 85 | 86 | {-functions :: [(String, (Code, Fix, Sig))] 87 | functions = 88 | [("+", (Tk_plus, Infix, numOp)), 89 | ("*", (Tk_multiply, Infix, numOp)), 90 | ("/", (Tk_divide, Infix, numOp)), 91 | ("-", (Tk_subtract, Infix, numOp)), 92 | ("#", (Tk_hash, Infix, ppOp)), 93 | ("$", (Tk_dollar, Infix, Sig [C_WildCard, C_WildCard] $ T_F (T_F (T_Constraint 0) (T_Constraint 1)) (T_F (T_Constraint 0) (T_Constraint 1)))), 94 | ("every", (Tk_every, Prefix, i_pf_p)), 95 | ("rev", (Tk_rev, Prefix, pOp)), 96 | ("pure", (Tk_pure, Prefix, Sig [C_WildCard] $ T_F (T_Constraint 0) (T_Pattern $ T_Constraint 0))) 97 | ] 98 | where pi_pf_p = Sig [C_WildCard] $ T_F (T_Pattern T_Int) 99 | (T_F (T_F (T_Pattern $ T_Constraint 0) (T_Pattern $ T_Constraint 0)) 100 | (T_F (T_Pattern $ T_Constraint 0) (T_Pattern $ T_Constraint 0)) 101 | ) 102 | i_pf_p = Sig [C_WildCard] $ T_F T_Int 103 | (T_F (T_F (T_Pattern $ T_Constraint 0) (T_Pattern $ T_Constraint 0)) 104 | (T_F (T_Pattern $ T_Constraint 0) (T_Pattern $ T_Constraint 0)) 105 | ) 106 | numOp = Sig [C_OneOf[T_Float,T_Int,T_Rational]] 107 | $ T_F (T_Constraint 0) $ T_F (T_Constraint 0) (T_Constraint 0) 108 | -- $ T_F (T_Pattern $ T_Constraint 0) $ T_F (T_Pattern $ T_Constraint 0) (T_Pattern $ T_Constraint 0) 109 | sOp = Sig [] $ T_F (T_Pattern $ T_String) (T_Pattern $ T_String) 110 | pOp = Sig [C_WildCard] $ T_F (T_Pattern $ T_Constraint 0) (T_Pattern $ T_Constraint 0) 111 | ppOp = Sig [C_WildCard] $ T_F (T_Pattern $ T_Constraint 0) $ T_F (T_Pattern $ T_Constraint 0) (T_Pattern $ T_Constraint 0) 112 | {- 113 | floatOp = Sig [] $ T_F (T_Pattern T_Float) (T_F (T_Pattern T_Float) (T_Pattern T_Float)) 114 | floatPat = Sig [] $ T_Pattern T_Float 115 | mapper = Sig [T_WildCard, T_WildCard] $ T_F (T_F (T_Constraint 0) (T_Constraint 1)) $ T_F (T_Pattern (T_Constraint 0)) (T_Pattern (T_Constraint 1)) 116 | stringToPatMap = Sig [] $ T_F (T_Pattern T_String) (T_Pattern T_Map) 117 | floatToPatMap = Sig [] $ T_F (T_Pattern T_Float) (T_Pattern T_Map) 118 | number = OneOf [Pattern Float, Pattern Int] 119 | number = T_Pattern (T_OneOf[T_Float,T_Int]) 120 | -} 121 | -} 122 | 123 | arity :: Type -> Int 124 | arity (T_F _ b) = (arity b) + 1 125 | arity _ = 0 126 | 127 | isFn :: Type -> Bool 128 | isFn (T_F _ _) = True 129 | isFn _ = False 130 | 131 | setAt :: [a] -> Int -> a -> [a] 132 | setAt xs i x = take i xs ++ [x] ++ drop (i + 1) xs 133 | 134 | fitsConstraint :: Type -> [Constraint]-> Int -> Bool 135 | fitsConstraint t cs i | i >= length cs = error "Internal error - no such constraint" 136 | | c == C_WildCard = True 137 | | otherwise = or $ map (\t' -> fits' t $ Sig cs t') $ options c 138 | where c = cs !! i 139 | options (C_OneOf cs) = cs 140 | options _ = [] -- can't happen.. 141 | 142 | 143 | fits' :: Type -> Sig -> Bool 144 | fits' t s = isJust $ fits t s 145 | 146 | fits :: Type -> Sig -> Maybe ([(Int, Type)]) 147 | fits t (Sig cs (T_Constraint i)) = if (fitsConstraint t cs i) 148 | then Just [(i, t)] 149 | else Nothing 150 | fits (T_F arg result) (Sig c (T_F arg' result')) = do as <- fits arg (Sig c arg') 151 | bs <- fits result (Sig c result') 152 | return $ as ++ bs 153 | fits (T_Pattern a) (Sig c (T_Pattern b)) = fits a (Sig c b) 154 | fits (T_List a) (Sig c (T_List b)) = fits a (Sig c b) 155 | fits a (Sig _ b) = if a == b 156 | then Just [] 157 | else Nothing 158 | 159 | -- How can b produce target a? 160 | -- Will either return the target need, or a function that can 161 | -- return it, or nothing. 162 | fulfill :: Type -> Sig -> Maybe Type 163 | fulfill n c = do (cs, t) <- fulfill' n c 164 | resolveConstraint cs t 165 | 166 | fulfill' :: Type -> Sig -> Maybe ([(Int, Type)], Type) 167 | fulfill' need contender@(Sig c (T_F arg result)) 168 | | arityD == 0 = do cs <- fits need contender 169 | return (cs, need) 170 | | arityD > 0 = (T_F arg <$>) <$> fulfill' need (Sig c result) 171 | | otherwise = Nothing 172 | where arityD = arity (is contender) - arity need 173 | fulfill' need contender = do cs <- fits need contender 174 | return (cs, need) 175 | 176 | resolveConstraint :: [(Int, Type)] -> Type -> Maybe Type 177 | resolveConstraint cs (T_Constraint n) = lookup n cs 178 | resolveConstraint cs (T_F a b) 179 | = T_F <$> resolveConstraint cs a <*> resolveConstraint cs b 180 | resolveConstraint cs (T_Pattern t) = T_Pattern <$> resolveConstraint cs t 181 | resolveConstraint cs (T_List t) = T_List <$> resolveConstraint cs t 182 | resolveConstraint _ t = Just t 183 | 184 | -------------------------------------------------------------------------------- /src/Sound/Tidal2/Signal.hs: -------------------------------------------------------------------------------- 1 | {-# LANGUAGE DeriveFunctor, OverloadedStrings #-} 2 | 3 | -- (c) Alex McLean 2022 4 | -- Shared under the terms of the GNU Public License v. 3.0 5 | 6 | module Sound.Tidal2.Signal where 7 | 8 | import Data.Ratio 9 | import Data.Fixed (mod') 10 | import Data.Maybe (catMaybes) 11 | import qualified Data.Map.Strict as Map 12 | import Control.Applicative (liftA2) 13 | 14 | import Sound.Tidal2.Time 15 | import Sound.Tidal2.Value 16 | import Sound.Tidal2.Pattern 17 | 18 | import Prelude hiding ((<*), (*>)) 19 | 20 | -- ************************************************************ -- 21 | -- Core definition of a Signal 22 | 23 | -- | An event - a value, its 'whole' timespan, and the timespan that 24 | -- its active (called a 'part' in tidal v1) 25 | data Event a = Event {whole :: Maybe Span, 26 | active :: Span, value :: a 27 | } 28 | deriving (Show, Functor) 29 | 30 | -- | A pattern - a function from a timespan to a list of events active 31 | -- during that timespan 32 | data Signal a = Signal {query :: Span -> [Event a]} 33 | deriving (Functor) 34 | 35 | instance Show a => Show (Signal a) where 36 | show pat = show $ query pat (Span 0 1) 37 | 38 | -- ************************************************************ -- 39 | 40 | -- | A control pattern as a map from strings to values 41 | type ControlSignal = Signal (Map.Map String Value) 42 | 43 | -- ************************************************************ -- 44 | 45 | instance Applicative Signal where 46 | pure = steady 47 | (<*>) = app (liftA2 sect) 48 | 49 | -- | Apply a pattern of values to a pattern of functions, given a 50 | -- function to merge the 'whole' timespans 51 | app :: (Maybe Span -> Maybe Span -> Maybe Span) -> Signal (a -> b) -> Signal a -> Signal b 52 | app wf patf patv = Signal f 53 | where f s = concatMap (\ef -> catMaybes $ map (apply ef) evs) efs 54 | where efs = (query patf s) 55 | evs = (query patv s) 56 | apply ef ev = apply' ef ev (maybeSect (active ef) (active ev)) 57 | apply' ef ev Nothing = Nothing 58 | apply' ef ev (Just s') = Just $ Event (wf (whole ef) (whole ev)) s' (value ef $ value ev) 59 | 60 | -- | Alternative definition of <*>, which takes the wholes from the 61 | -- pattern of functions (unrelated to the <* in Prelude) 62 | (<*) :: Signal (a -> b) -> Signal a -> Signal b 63 | (<*) = app const 64 | 65 | -- | Alternative definition of <*>, which takes the wholes from the 66 | -- pattern of values (unrelated to the *> in Prelude) 67 | (*>) :: Signal (a -> b) -> Signal a -> Signal b 68 | (*>) = app (flip const) 69 | 70 | -- ************************************************************ -- 71 | 72 | instance Monad Signal where 73 | (>>=) = bind 74 | 75 | bind :: Signal a -> (a -> Signal b) -> Signal b 76 | bind = bindWhole (liftA2 sect) 77 | 78 | bindInner :: Signal a -> (a -> Signal b) -> Signal b 79 | bindInner = bindWhole const 80 | 81 | joinInner :: Signal (Signal a) -> Signal a 82 | joinInner s = bindInner s id 83 | 84 | bindOuter :: Signal a -> (a -> Signal b) -> Signal b 85 | bindOuter = bindWhole (flip const) 86 | 87 | joinOuter :: Signal (Signal a) -> Signal a 88 | joinOuter s = bindOuter s id 89 | 90 | bindWhole :: (Maybe Span -> Maybe Span -> Maybe Span) -> Signal a -> (a -> Signal b) -> Signal b 91 | bindWhole chooseWhole pv f = Signal $ \s -> concatMap (match s) $ query pv s 92 | where match s e = map (withWhole e) $ query (f $ value e) (active e) 93 | withWhole e e' = e' {whole = chooseWhole (whole e) (whole e')} 94 | 95 | -- ************************************************************ -- 96 | -- Pattern instance 97 | 98 | instance Pattern Signal where 99 | slowcat = sigSlowcat 100 | _fast = _sigFast 101 | _early = _sigEarly 102 | silence = sigSilence 103 | atom = sigAtom 104 | stack = sigStack 105 | _patternify f x pat = joinInner $ (`f` pat) <$> x 106 | 107 | -- ************************************************************ -- 108 | -- General hacks 109 | 110 | instance Show (a -> b) where 111 | show _ = "" 112 | 113 | -- ************************************************************ -- 114 | -- Time utilities 115 | 116 | withEventSpan :: (Span -> Span) -> Signal a -> Signal a 117 | withEventSpan spanf pat = Signal f 118 | where f s = map (\e -> e {active = spanf $ active e, 119 | whole = spanf <$> whole e 120 | }) $ query pat s 121 | 122 | withEventTime :: (Rational -> Rational) -> Signal a -> Signal a 123 | withEventTime timef pat = Signal f 124 | where f s = map (\e -> e {active = withSpanTime timef $ active e, 125 | whole = withSpanTime timef <$> whole e 126 | }) $ query pat s 127 | 128 | withSpanTime :: (Rational -> Rational) -> Span -> Span 129 | withSpanTime timef (Span b e) = Span (timef b) (timef e) 130 | 131 | withQuery :: (Span -> Span) -> Signal a -> Signal a 132 | withQuery spanf pat = Signal $ \s -> query pat $ spanf s 133 | 134 | withQueryTime :: (Rational -> Rational) -> Signal a -> Signal a 135 | withQueryTime timef = withQuery (withSpanTime timef) 136 | 137 | -- ************************************************************ -- 138 | -- Fundamental patterns 139 | 140 | sigSilence :: Signal a 141 | sigSilence = Signal (\_ -> []) 142 | 143 | -- | Repeat discrete value once per cycle 144 | sigAtom :: a -> Signal a 145 | sigAtom v = Signal f 146 | where f s = map (\s' -> Event (Just $ wholeCycle $ begin s') s' v) (splitSpans s) 147 | wholeCycle :: Rational -> Span 148 | wholeCycle t = Span (sam t) (nextSam t) 149 | 150 | -- | A continuous value 151 | steady :: a -> Signal a 152 | steady v = waveform (const v) 153 | 154 | -- ************************************************************ -- 155 | -- Waveforms 156 | 157 | -- | A continuous pattern as a function from time to values. Takes the 158 | -- midpoint of the given query as the time value. 159 | waveform :: (Rational -> a) -> Signal a 160 | waveform timeF = Signal {query = f} 161 | where f (Span b e) = [Event {whole = Nothing, 162 | active = (Span b e), 163 | value = timeF $ b+((e - b)/2) 164 | } 165 | ] 166 | 167 | -- | Sawtooth waveform 168 | saw :: Signal Rational 169 | saw = waveform $ \t -> mod' t 1 170 | 171 | saw2 :: Signal Rational 172 | saw2 = toBipolar saw 173 | 174 | -- | Sine waveform 175 | sine :: Fractional a => Signal a 176 | sine = fromBipolar sine2 177 | 178 | sine2 :: Fractional a => Signal a 179 | sine2 = waveform $ \t -> realToFrac $ sin ((pi :: Double) * 2 * fromRational t) 180 | 181 | -- ************************************************************ -- 182 | -- Signal manipulations 183 | 184 | splitQueries :: Signal a -> Signal a 185 | splitQueries pat = Signal $ \s -> (concatMap (query pat) $ splitSpans s) 186 | 187 | -- | Concatenate a list of patterns (works a little differently from 188 | -- 'real' tidal, needs some work) 189 | sigSlowcat :: [Signal a] -> Signal a 190 | sigSlowcat pats = splitQueries $ Signal queryCycle 191 | where queryCycle s = query (pats !! (mod (floor $ begin s) n)) s 192 | n = length pats 193 | 194 | _sigFast :: Rational -> Signal a -> Signal a 195 | _sigFast t pat = withEventTime (/t) $ withQueryTime (*t) $ pat 196 | 197 | _sigEarly :: Rational -> Signal a -> Signal a 198 | _sigEarly t pat = withEventTime (subtract t) $ withQueryTime (+ t) $ pat 199 | 200 | sigStack :: [Signal a] -> Signal a 201 | sigStack pats = Signal $ \s -> concatMap (\pat -> query pat s) pats 202 | 203 | squash :: Rational -> Signal a -> Signal a 204 | squash into pat = splitQueries $ withEventSpan ef $ withQuery qf pat 205 | where qf (Span s e) = Span (sam s + (min 1 $ (s - sam s) / into)) (sam s + (min 1 $ (e - sam s) / into)) 206 | ef (Span s e) = Span (sam s + (s - sam s) * into) (sam s + (e - sam s) * into) 207 | 208 | squashTo :: Rational -> Rational -> Signal a -> Signal a 209 | squashTo b e = _late b . squash (e-b) 210 | 211 | -- ************************************************************ -- 212 | -- Higher order transformations 213 | 214 | --every :: Int -> (Signal a -> Signal a) -> Signal a -> Signal a 215 | --every n f pat = splitQueries $ Signal 216 | 217 | -- ************************************************************ -- 218 | 219 | (#) :: ControlSignal -> ControlSignal -> ControlSignal 220 | (#) a b = Map.union <$> a <*> b 221 | 222 | (|+|) :: Num a => Signal a -> Signal a -> Signal a 223 | (|+|) a b = (+) <$> a <*> b 224 | 225 | (|+) :: Num a => Signal a -> Signal a -> Signal a 226 | (|+) a b = ((+) <$> a) <* b 227 | 228 | (+|) :: Num a => Signal a -> Signal a -> Signal a 229 | (+|) a b = ((+) <$> a) *> b 230 | 231 | -- ************************************************************ -- 232 | 233 | sound :: Signal String -> ControlSignal 234 | sound pat = (Map.singleton "sound" . S) <$> pat 235 | 236 | note :: Signal Double -> ControlSignal 237 | note pat = (Map.singleton "note" . F) <$> pat 238 | 239 | -- ************************************************************ -- 240 | -------------------------------------------------------------------------------- /src/Sound/Tidal2/Parse.hs: -------------------------------------------------------------------------------- 1 | {-# LANGUAGE TypeSynonymInstances, FlexibleInstances, UndecidableInstances #-} 2 | 3 | module Sound.Tidal2.Parse where 4 | 5 | import Control.Monad (void) 6 | import Data.Void 7 | import Text.Megaparsec hiding (State) 8 | import Text.Megaparsec.Char 9 | import Text.Megaparsec.Debug 10 | import Control.Monad.State (evalState, State, get, put) 11 | import qualified Text.Megaparsec.Char.Lexer as L 12 | import Data.Ratio 13 | import Control.Monad (unless) 14 | 15 | import Sound.Tidal2.Pattern hiding ((*>),(<*)) 16 | import Sound.Tidal2.Types 17 | 18 | -- ************************************************************ -- 19 | -- Parser 20 | -- 21 | 22 | -- type Parser = ParsecT Void String (State Type) 23 | 24 | type Parser = Parsec Void String 25 | 26 | data RhythmT a = Sequence 27 | 28 | sc :: Parser () 29 | sc = L.space (void spaceChar) lineCmnt blockCmnt 30 | where lineCmnt = L.skipLineComment "//" 31 | blockCmnt = L.skipBlockComment "/*" "*/" 32 | 33 | lexeme :: Parser a -> Parser a 34 | lexeme = L.lexeme sc 35 | 36 | integer :: Parser Int 37 | integer = lexeme L.decimal 38 | 39 | signedInteger :: Parser Int 40 | signedInteger = L.signed (return ()) $ lexeme L.decimal 41 | 42 | stringLiteral :: Parser String 43 | stringLiteral = char '\"' *> manyTill L.charLiteral (char '\"') 44 | 45 | symbol :: String -> Parser String 46 | symbol = L.symbol sc 47 | 48 | parens,braces,angles,brackets :: Parser a -> Parser a 49 | parens = between (symbol "(") (symbol ")") 50 | braces = between (symbol "{") (symbol "}") 51 | angles = between (symbol "<") (symbol ">") 52 | brackets = between (symbol "[") (symbol "]") 53 | 54 | comma :: Parser String 55 | comma = symbol "," 56 | 57 | identifier :: Parser String 58 | identifier = lexeme $ do x <- lowerChar 59 | xs <- many $ choice [alphaNumChar, 60 | single '_', 61 | single '\'' 62 | ] 63 | return $ x:xs 64 | 65 | -- ************************************************************ -- 66 | 67 | pSequence :: Parser R 68 | pSequence = R_Subsequence <$> many pStep 69 | 70 | pStep :: Parser R 71 | pStep = do r <- pRhythm 72 | do void $ symbol "@" 73 | ratio <- pNumber 74 | return $ R_Duration ratio r 75 | <|> return r 76 | 77 | pBracket :: Parser R 78 | pBracket = R_Silence <$ symbol "~" 79 | <|> brackets (R_StackCycles <$> pSequence `sepBy` comma) 80 | <|> braces (R_StackSteps <$> pSequence `sepBy` comma) 81 | <|> angles (R_StackStep <$> pSequence `sepBy` comma) 82 | -- <|> parens 83 | 84 | pRhythm :: Parser R 85 | pRhythm = pBracket <|> R_Atom <$> identifier 86 | 87 | pRatio :: Parser Rational 88 | pRatio = do try $ (toRational <$> L.float) 89 | <|> do num <- L.decimal 90 | denom <- do single '%' 91 | L.decimal 92 | <|> return 1 93 | return $ num % denom 94 | 95 | -- ************************************************************ -- 96 | 97 | pNumber :: Parser Code 98 | pNumber = lexeme $ do i <- L.signed (return ()) L.decimal 99 | do char '.' 100 | d <- (read . ('0':) . ('.':)) <$> some digit 101 | return $ Cd_Float $ if i >=0 then (fromIntegral i) + d else (fromIntegral i) - d 102 | <|> do char '%' 103 | d <- L.decimal 104 | return $ Cd_Rational $ (fromIntegral i) % (fromIntegral d) 105 | <|> (return $ Cd_Int i) 106 | where digit = oneOf ['0'..'9'] 107 | 108 | pInfix :: Parser Code 109 | pInfix = do l <- Just <$> pClosed 110 | <|> return Nothing 111 | o <- pOp 112 | r <- Just <$> pOpen 113 | <|> return Nothing 114 | return $ Cd_Op l o r 115 | 116 | pClosed :: Parser Code 117 | pClosed = try pNumber -- use try to avoid consuming + / - 118 | <|> pName 119 | <|> parens pOpen 120 | <|> Cd_R <$> pBracket 121 | 122 | pOpen :: Parser Code 123 | pOpen = try pInfix <|> pFunc <|> pClosed 124 | 125 | pOp :: Parser Code 126 | pOp = 127 | Cd_dollar <$ symbol "$" 128 | <|> Cd_multiply <$ symbol "*" 129 | <|> Cd_divide <$ symbol "/" 130 | <|> Cd_plus <$ symbol "+" 131 | <|> Cd_subtract <$ symbol "-" 132 | 133 | pName :: Parser Code 134 | pName = Cd_name <$> identifier 135 | 136 | pFunc :: Parser Code 137 | pFunc = do name <- pName 138 | args <- many pClosed 139 | return $ foldr Cd_App name args 140 | 141 | 142 | class Parseable a where 143 | to :: Code -> Maybe a 144 | to _ = Nothing 145 | toType :: Type 146 | reify :: String -> Maybe a 147 | reify _ = Nothing 148 | 149 | instance Parseable String where 150 | to (Cd_String s) = Just s 151 | to _ = Nothing 152 | toType = T_String 153 | 154 | instance Parseable Int where 155 | to (Cd_Int i) = Just i 156 | -- to (Cd_App (Cd_name a) (Cd_Int i)) = do f <- reify a 157 | -- return $ f i 158 | -- to (Cd_App (Cd_App (Cd_name a) (Cd_Int i)) (Cd_Int j)) = 159 | -- do f <- reify a 160 | -- return $ f i j 161 | -- to (Cd_App x (Cd_Int i)) = do f <- to x 162 | -- return $ f i 163 | to _ = Nothing 164 | toType = T_Int 165 | 166 | --instance (Parseable a, Parseable b) => Parseable (a -> b) where 167 | -- toType = t 168 | 169 | args :: Code -> [Code] 170 | args (Cd_App a b) = (args a) ++ [b] 171 | args (a@(Cd_name _)) = [a] 172 | args a = fail $ "unexpected arglist head:" ++ show a 173 | 174 | 175 | {- 176 | instance Parseable (Int -> Int) where 177 | reify "plusone" = Just (+1) 178 | reify _ = Nothing 179 | 180 | instance Parseable (Int -> Int -> Int) where 181 | reify "plus" = Just (+) 182 | reify _ = Nothing 183 | -} 184 | 185 | {- 186 | 187 | -- ************************************************************ -- 188 | 189 | 190 | 191 | pIdentifier :: Parser String 192 | pIdentifier = lexeme $ do x <- lowerChar 193 | xs <- many $ choice [alphaNumChar, 194 | single '_', 195 | single '\'' 196 | ] 197 | return $ x:xs 198 | 199 | pOperator :: Parser String 200 | pOperator = lexeme $ some (oneOf ("<>?!|-~+*%$'.#" :: [Char])) 201 | 202 | 203 | pClosed :: Type -> Parser Code 204 | pClosed need = case need of 205 | T_Int -> Cd_Int <$> signedInteger 206 | T_Rational -> Cd_Rational <$> pRatio 207 | T_String -> Cd_String <$> stringLiteral 208 | T_Bool -> Cd_Bool True <$ symbol "True" 209 | <|> Cd_Bool False <$ symbol "False" 210 | _ -> fail "Not a value" 211 | <|> parens (pOpen need) 212 | 213 | pOpen :: Type -> Parser Code 214 | pOpen need = pFn need <|> pInfix need <|> pClosed need 215 | 216 | pInfix :: Type -> Parser Code 217 | pInfix need = do (tok, T_F a (T_F b c)) <- pPeekOp need 218 | a' <- dbg "left" $ optional $ try $ pClosed a -- 'try' needed due to numerical + prefix.. 219 | pOp 220 | b' <- optional $ try $ pClosed b 221 | let t = case (a', b') of 222 | (Nothing, Nothing) -> (T_F a $ T_F b c) 223 | (Just _, Nothing) -> (T_F b c) 224 | (Nothing, Just _) -> (T_F a c) 225 | (Just _, Just _) -> c 226 | unless (need == t) $ fail $ "Expected type " ++ show need 227 | return $ Cd_Op a' tok b' 228 | 229 | 230 | pFn :: Type -> Parser Code 231 | pFn need = 232 | do ident <- dbg "identifier" pIdentifier 233 | (tok, t) <- case (lookup ident functions) of 234 | Just (tok, Prefix, identSig) -> 235 | case (fulfill need identSig) of 236 | Just t -> return (tok, t) 237 | Nothing -> fail $ "Bad type of " ++ ident ++ "\nfound: " ++ show identSig ++ "\ntarget: " ++ show need 238 | Nothing -> fail "Unknown function" 239 | _ -> fail "TODO - handle infix section" 240 | args t (arity t - arity need) tok 241 | 242 | args :: Type -> Int -> Code -> Parser Code 243 | args _ 0 tok = return tok 244 | args need n tok | n < 0 = error "Internal error, negative args?" 245 | | otherwise = do let (T_F arg result) = need 246 | argtok <- pClosed arg 247 | args result (n - 1) (Cd_App tok argtok) 248 | 249 | pNumber :: Parser () 250 | pNumber = lexeme $ do optional $ char '-' 251 | some digit 252 | optional $ try $ do oneOf ['.', '%'] 253 | some digit 254 | return () 255 | where digit = oneOf ['0'..'9'] 256 | 257 | 258 | pSlurpTerm :: Parser () 259 | pSlurpTerm = do parens pSlurpAll 260 | <|> brackets pSlurpAll 261 | <|> braces pSlurpAll 262 | <|> angles pSlurpAll 263 | <|> (stringLiteral >> return ()) 264 | <|> (pIdentifier >> return ()) 265 | <|> try pNumber 266 | return () 267 | 268 | pSlurpAll :: Parser () 269 | pSlurpAll = do many (pSlurpTerm <|> (pOp >> return ())) 270 | return () 271 | 272 | pOp :: Parser String 273 | pOp = lexeme $ some $ oneOf "!#$%&*+./<=>?@\\^|-~" 274 | 275 | pPeekOp :: Type -> Parser (Code, Type) 276 | pPeekOp need = dbg "pPeekOp" $ try $ lookAhead $ 277 | do many pSlurpTerm 278 | op <- pOp 279 | case (lookup op functions) of 280 | Just (tok, Infix, opSig) -> 281 | case (fulfill need opSig) of 282 | Just t -> return (tok, t) 283 | Nothing -> fail $ "Bad type of op " ++ op ++ "\nfound: " ++ show opSig ++ "\ntarget: " ++ show need 284 | Nothing -> fail $ "Unknown operator " ++ op 285 | _ -> fail "Unexpected prefix function.." 286 | 287 | -} 288 | -------------------------------------------------------------------------------- /old/paper.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: Alternate Timelines for TidalCycles 3 | author: Alex McLean 4 | address: Then Try This 5 | email: alex@slab.org 6 | --- 7 | 8 | # INTRODUCTION 9 | 10 | The TidalCycles (or *Tidal* for short) live coding environment has been developed since around 2009, via several rewrites of its core representation. Rather than having fixed goals, this development has been guided by use, motivated by the open aim to make music. This development process can be seen as a long-form improvisation, with insights into the nature of Tidal gained through the process of writing it, feeding back to guide the next steps of development. 11 | 12 | This brings the worrying thought that key insights will have been missed along this development journey, that would otherwise have lead to very different software. Indeed participants at beginners' workshops that I have lead or co-lead have often asked questions without good answers, because they made deficiencies or missing features in the software clear. It is well known that a beginner's mind is able to see much that an expert has become blind to. Running workshops are an excellent way to find new development ideas, but the present paper explores a different technique - the rewrite. 13 | 14 | # THE REWRITE 15 | 16 | I have re-written Tidal several times before [@mcleanMakingProgrammingLanguages2014], or at least largely re-written the inner representation of Tidal patterns and refactored its library of combinators. This involved working in a fresh source folder, but copy-and-pasting a large part of the code, function-by-function from old to new, re-appraising and rewriting as I went. By focussing on the representation, and taking advantages of insights gained since the last rework, generally this involved deleting more code than I wrote. Certainly the type definitions and supporting code has become significantly shorter and clearer through the process of these rewrites. 17 | 18 | However the ongoing rewrite reported on here is as an attempt to recreate Tidal from scratch *without* reference to the existing codebase, as a 'clean room' rewrite. It began with a two-hour public live stream where I ‘thought aloud’ while rewriting Tidal's core representation of patterns as functions of time. The design of these innards has taken place over a decade, but this session could be viewed as replaying a condensed version of the thinking behind its design over a mere two hours. This points to a potentially useful research programme, where several people are invited to attempt a similar process of thinking aloud while remaking a core part of their system. 19 | 20 | The first motivation for this work was simply curiosity, after participating in a discussion about rewriting generative systems from scratch^[The discussion took place in July 2021, organised by the on-the-fly research group. Mateo Tonatiuh described losing the source code for one of his music systems, remaking it, and finding the new version behaved very differently from the original.] - how different would it turn out? Would it be better or worse? What insights will be gained, and how will this work feed back into mainline Tidal development? Further motivations have emerged during the rewrite; the clarity from refactoring, ideas to formalise Tidal’s polymetric sequences underlying its ‘mini-notation’, ways to escape Haskell syntax with a custom parser, and facilitating 'ports' of Tidal to other languages. 21 | 22 | ## The First Two Hours 23 | 24 | I began the rewrite as a two-hour live stream, to see how much of Tidal I could write in that time.^[An archive of the live stream is available here: ] I wasn't sure how interactive or interesting the stream would be, but in the event, I happily talked continuously throughout, with an eye on feedback in the live chat. Surprisingly for me, this felt more engaged than the many times I have streamed musical live coding performances. It felt good to respond to questions and read encouraging messages, while sharing quite an intensive experience of writing the foundations of a system from scratch. 25 | 26 | Although this was what you might call "night science", done out of curiosity rather than to respond to a clear research question or design requirement, this approach has some relation to the "think aloud" and "talk aloud" protocols 27 | [@ericssonProtocolAnalysisVerbal1984], which are usability research techniques which have for example been applied in the Psychology of Programming field [@wallace2002] to investigate programming languages as user interfaces. From this experience I have found it possible to 'think aloud' while writing a significant part of a representation for a live coding system, during a relatively short period of time. The design of Tidal's innards has taken place over 12 years, but this session could be viewed as replaying a condensed version of the thinking behind its design over a mere two hours. This points to a potentially useful research programme, where several people are invited to attempt a similar process of thinking aloud while remaking a core part of their system. There has been little in the way of comparative research into the thinking that goes into live coding language design, and this could be a fruitful approach to take. However I only offer this thought for future work, and in-depth analysis of the live stream itself is out of context for this paper. 28 | 29 | The outcome of the stream^[See the following link for the code resulting from the two hour live stream: ] was 114 code lines^[Calculated with the *cloc* utility: ], roughly two lines per minute, although 37 of these lines were largely redundant type definitions. At the time of writing, additional work tidying and expanding on this work has roughly trebled this line count since, and it is this version that I will compare with the mainline Tidal codebase.^[The state of the repository at the time of writing: ] 30 | 31 | ## Applicative Functors and Monads 32 | 33 | The rewrite focussed on the representation of pattern, and the core functional structures. At this point, Tidal's representation of pattern is well defined, and the rewritten version does not show any significant differences with the original. However the functions representing how patterns are combined look very different. 34 | 35 | The rewrite includes the following definition of the standard `<*>` operator and supplemental `<*` and `*>`, which form the basis of Tidal's family of operators for combining patterns (`#`, `+|`, `|*`, and friends). For example these definitions allow two patterns of numbers to be added together, or two patterns of synthesiser effects to be combined, even if the patterns have very different structures. This forms part of Tidal's definition of an 'applicative functor'. Haskell programmers should note that the use of `<*` and `*>` is unrelated to their usual definition and use in Haskell, rather they define alternate behaviour to `<*>`. 36 | 37 | ```haskell 38 | app wf patf patv = Pattern f 39 | where f s = concatMap (\ef -> catMaybes $ map (apply ef) evs) efs 40 | where efs = (query patf s) 41 | evs = (query patv s) 42 | apply ef ev = apply' ef ev (maybeSect (active ef) (active ev)) 43 | apply' ef ev Nothing = Nothing 44 | apply' ef ev (Just s') = 45 | Just $ Event (wf (whole ef) (whole ev)) s' (value ef $ value ev) 46 | 47 | (<*>) :: Pattern (a -> b) -> Pattern a -> Pattern b 48 | (<*>) = app (liftA2 sect) 49 | 50 | (<*) :: Pattern (a -> b) -> Pattern a -> Pattern b 51 | (<*) = app const 52 | 53 | (*>) :: Pattern (a -> b) -> Pattern a -> Pattern b 54 | (*>) = app (flip const) 55 | ``` 56 | 57 | Unlike in the current 'mainline' Tidal, we can see from the above that the three operators are based on a single function `app`, which does the work of matching events from the pattern of events with the pattern of values. Often matching events will only partly overlap, in which case are treated as fragments of an original 'whole' event. This whole is either taken from the pattern of functions (using `<*`), the pattern of values (using `*>`), or the intersection of the two (`<*>`). In the case of addition, the Tidal operators built form these would be `|+`, `+|` and `|+|` respectively, where structure is said to come from the 'left', 'right' or 'both'. I won't go into further detail of the workings here, but if I did I would find it a lot easier to write about than the original definitions in 'mainline' Tidal, which are around 2.5 times longer and far less clear. 58 | 59 | The following is the rewritten version of Tidal's 'bind' operations, which again provides core functionality for how patterns are combined. In particular it is what makes 'patterned parameters' possible, where for example when using the `fast` function to speed a pattern up, you can also pattern the amount by which it is sped up by. This function (which forms part of the Tidal's definition of a 'monad') is what leads to the popular refrain that in Tidal, it's *patterns all the way down*. 60 | 61 | ```haskell 62 | bindWhole :: (Maybe Span -> Maybe Span -> Maybe Span) -> Pattern a -> (a -> Pattern b) -> Pattern b 63 | bindWhole chooseWhole pv f = Pattern $ \s -> concatMap (match s) $ query pv s 64 | where match s e = map (withWhole e) $ query (f $ value e) (active e) 65 | withWhole e e' = e' {whole = chooseWhole (whole e) (whole e')} 66 | 67 | bind :: Pattern a -> (a -> Pattern b) -> Pattern b 68 | bind = bindWhole (liftA2 sect) 69 | 70 | bindInner :: Pattern a -> (a -> Pattern b) -> Pattern b 71 | bindInner = bindWhole const 72 | 73 | bindOuter :: Pattern a -> (a -> Pattern b) -> Pattern b 74 | bindOuter = bindWhole (flip const) 75 | ``` 76 | 77 | Again, this is several times smaller than the current equivalent definitions in the 'mainline' Tidal, and far clearer. My reason for including both code snippets here though is to point out the similarities between the definitions of `<*>`, `<*` and `*>`, and those of `bind`, `bindInner` and `bindOuter`. This carries a core insight gained during the rewrite process, that when combining patterns, a common question is that when combining two event fragments, how do you choose what they are a fragment *of*? This insight helps both understand and explain Tidal's approach to combining patterns in time. 78 | 79 | I should briefly note that despite the above talk of combining events, Tidal patterns are not data structures, but functions of time. The above functions combine behaviour as functions, but do not actually do any matching of events until later, when the pattern is queried for events, usually by Tidal's scheduler. This is good, because time is infinite, and so procedurally combining all the possible events in two patterns would take forever. 80 | 81 | # REPRESENTING SEQUENCES 82 | 83 | The rewrite has also been an opportunity to rethink how sequences are represented. TidalCycles is often looked on with some suspicion in the Haskell community for its apparent heavy use of strings to represent polymetric sequences as 'mini-notation'. The pejorative term 'stringly typed' (as opposed to 'strongly typed') has been used. To some extent this is a misunderstanding, the double-quoted strings are 'overloaded', immediately parsed into 'well-typed' functions of time with no other string manipulation. With some exceptions, a rhythm written in the mini-notation is also possible to express directly with Tidal's library of Haskell functions; the mini-notation, inspired by Bernard Bel's *Bol processor* [@belRationalizingMusicalTime2001] simply lets you do so more quickly and succinctly. 84 | 85 | Nonetheless, it is true that Tidal does not formally represent the polymetric sequences parsed by the mini-notation. 0nce they are parsed into a Tidal pattern, the metric structure of the sequence is locked away inside an opaque function of time. This rewrite process was therefore an opportunity to consider how Tidal's current representation of patterns as functions of time could be augmented with equally well formalised representation of rhythms as polymetric sequences. 86 | 87 | To this end, the rewrite currently includes a type for representing rhythm as follows: 88 | ```haskell 89 | data Rhythm a = Atom a 90 | | Silence 91 | | Subsequence {rSteps :: [Step a] } 92 | | StackCycles {rRhythms :: [Rhythm a]} 93 | | StackSteps {rPerCycle :: Rational, 94 | rRhythms :: [Rhythm a] 95 | } 96 | | Patterning {rFunction :: Pattern a -> Pattern a, 97 | rRhythm :: Rhythm a 98 | } 99 | ``` 100 | 101 | An initial aim for this is to be able to represent mini-notation-alike structures in Haskell types, in order to allow Tidal to engage more directly with the world of stateful patterning procedures common in algorithmic music, such as L-Systems, Markov chains, cellular automata and so on. A longer term aim however is to escape Haskell syntax completely. The idea here is that once everything is represented in Haskell, it becomes easier to create something like a mini-notation that embraces the full capability of Tidal. Consider the following piece of design fiction: 102 | ``` 103 | jux <(rev) (iter 4)> $ sound [bd (every 3 (fast 4) [sn])] 104 | ``` 105 | The above pattern is not valid Tidal code as we currently know it, and appears to be a jumble of mini-notation and Tidal functions. Indeed, earlier I mentioned that running workshops is a great way to access beginners' minds for fresh perspectives, and I have often seen Tidal beginner workshop participants write code like the above. This raises the question, why *shouldn't* we be able to jumble up these different constructs? We could simply say that `[]` and `{}` allows us to jump into mini-notation-alike rhythms (where multiple subsequences are combined cycle-wise or beat-wise respectively) and `()` allows us to jump back into specifying pattern transformation functions. 106 | 107 | In fact, we already have a parser for Tidal as-is that could support such experimentation, the 'MiniTidal' parser created by David Ogborn, used at scale as part of his web-based Estuary live coding environment[@ogborn2017]. There seems to be a path laid out then, for Tidal to first become more clearly formalised in Haskell, in order to then support more flexible, experimental syntax beyond Haskell, such as the above. 108 | 109 | # VORTEX - A Tidal 'Port' to the Python Programming Language 110 | 111 | This leads to related possibilities offered up by this rewrite - porting Tidal outside of Haskell completely. Now that the core 'innards' of Tidal have been significantly clarified, particularly the applicative and monadic functions shared earlier, it could be easier to port Tidal to other languages. In the past I have sometimes wondered whether it is even practically possible to port Tidal to another language, when it use relies so much on Haskell features of strict types, partial application, type inference and so on. I took the opportunity to find out, by attempting to port Tidal to Python in collaboration with Sylvain Le Beux, Damián Silvani and Raphaël Forment. 112 | 113 | It proved to be fairly straightforward to port the core representation and applicative and monadic functions to python, and turning this into something useful became a collective effort, with python programmers in the Tidal community jumping in with ideas and core contributions. The project is codenamed 'vortex', and around two weeks in, already has a native live coding editor, growing documentation, testing framework, full integration with the Link synchronisation protocol, and of course is able to make sound via the SuperDirt synthesiser in SuperCollider. 114 | 115 | I still doubt that it would have been possible to make something quite like Tidal without the support of Haskell's excellent type system, but now it is made, it seems that the ideas and representations are readily transferable to quite different language environments. Nonetheless, there will surely be different trade-offs involved, according to the affordances of the language host, particularly where Tidal takes the form of an embedded domain specific language (as it does with Haskell and now Python). 116 | 117 | # CONCLUSION 118 | 119 | In summary, this work in rewriting Tidal was driven by curiosity, but lead to unexpected insights and opportunities, in terms of a clearer representation of patterns that opens up new possibilities for experimentation as discussed above. 120 | 121 | What I would especially like to highlight in conclusion is the possibility of opening up some of thinking that goes into creating live coding environments. Perhaps we should think about this quite differently from projecting screens in live coding performance; making live coding languages is after all quite a different mode compared to making music, visuals, choreography or other time-based art. Making live coding environments is an opportunity to get very deep in rethinking and restructuring our human relationship with time, where following and properly mapping out an idea might take a decade or more. 122 | 123 | Around 13 years into the development of Tidal I feel I'm only now properly able to grasp what Tidal is, and only starting to be able to properly articulate what it is to others. This 'clean room' rewriting process has helped with this aim, and I if you haven't already, I encourage other live coding language makers to try doing something similar. This is one way to give ourselves space, as dreamers of ways to dream. 124 | 125 | # ACKNOWLEDGMENTS 126 | 127 | Special thanks for the Tidal and live coding communities, especially Sylvain Le Beux, Damián Silvani and Raphaël Forment in collaborating on Vortex, the people joining the two-hour Tidal rewrite stream, and the organisers of and other participants in the On-The-Fly research group cantinas which helped keep me thinking during pandemic lockdown. 128 | 129 | This research is conducted partly during the PENELOPE project, with funding from the European Research Council (ERC) under the Horizon 2020 research and innovation programme of the European Union, grant agreement No 682711. It was also conducted during my fellowship as part of Then Try This, supported by a UKRI Future Leaders Fellowship [grant number MR/V025260/1]. 130 | 131 | # REFERENCES -------------------------------------------------------------------------------- /src/Sound/Tidal2/Sequence.hs: -------------------------------------------------------------------------------- 1 | -- (c) Aravind Mohandas, Alex McLean and contributors 2022 2 | -- Shared under the terms of the GNU Public License v3.0 3 | 4 | module Sound.Tidal2.Sequence where 5 | 6 | import Sound.Tidal2.Time 7 | import Sound.Tidal2.Value 8 | import Sound.Tidal2.Pattern 9 | 10 | import Data.List (inits) 11 | import Prelude hiding (span) 12 | import Data.Ratio 13 | 14 | -- import Sound.Tidal.Bjorklund 15 | 16 | data Strategy = JustifyLeft 17 | | JustifyRight 18 | | JustifyBoth 19 | | Expand 20 | | TruncateMax 21 | | TruncateMin 22 | | RepeatLCM 23 | | Centre 24 | | Squeeze 25 | deriving Show 26 | 27 | data Sequence a = Atom Rational a 28 | | Gap Rational 29 | | Sequence [Sequence a] 30 | | Stack [Sequence a] 31 | deriving Show 32 | 33 | instance Functor Sequence where 34 | fmap f (Atom x y) = Atom x (f y) 35 | fmap _ (Gap x) = Gap x 36 | fmap f (Sequence x) = Sequence $ map (fmap f) x 37 | fmap f (Stack y) = Stack (map (fmap f) y) 38 | 39 | instance Applicative Sequence where 40 | pure x = Atom 1 x 41 | (Atom x f) <*> something = 42 | let (p,q) = forTwo (Atom x f) something 43 | c = reAlign p q 44 | d = unwrap $ Sequence $ map (fmap f) c 45 | in d 46 | Gap x <*> something = 47 | let (p,_) = forTwo (Gap x) something 48 | in unwrap $ Sequence p 49 | Sequence f <*> something = 50 | let (p,q) = forTwo (Sequence f) something 51 | c = unwrapper $ reAlign p q 52 | d = unwrap $ Sequence $ funcMap p c 53 | in d 54 | Stack f <*> something = 55 | let d = map (<*> something) f 56 | in Stack d 57 | 58 | instance Monad Sequence where 59 | return = pure 60 | Atom _ y >>= f = f y 61 | Gap x >>= _ = Gap x 62 | Sequence x >>= f = Sequence $ map (>>= f) x 63 | Stack y >>= f = Stack (map (>>= f) y) 64 | 65 | instance Pattern Sequence where 66 | slowcat = seqSlowcat 67 | fastcat = seqFastcat 68 | _fast = _seqFast 69 | -- _early = _seqEarly 70 | silence = Gap 1 71 | atom = pure 72 | stack = seqStack 73 | -- _patternify f x pat = joinInner $ (`f` pat) <$> x 74 | 75 | -- -- | Takes sequence of functions and a sequence which have been aligned and applies the functions at the corresponding time points 76 | funcMap :: [Sequence (a->b)] -> [Sequence a] -> [Sequence b] 77 | funcMap [] _ = [] 78 | funcMap ((Atom x f):xs) y = 79 | let t = seqSpan (Atom x f) 80 | p = takeWhile (\r -> sum(map seqSpan r) <= t) $ inits y 81 | pTill = last p 82 | q = map (fmap f) pTill 83 | in q ++ funcMap xs (drop (length pTill) y) 84 | funcMap (Gap x:xs) y= 85 | let t = seqSpan (Gap x) 86 | p = takeWhile (\r -> sum(map seqSpan r) <= t) $ inits y 87 | pTill = last p 88 | q = Gap (sum $ map seqSpan pTill) 89 | in q : funcMap xs (drop (length pTill) y) 90 | funcMap (Sequence x:xs) y = funcMap (unwrapper x ++ xs) y 91 | funcMap _ _ = error "funcMap cannot be called on stack" 92 | 93 | -- | Mapping a function on entire sequence instead of just the values it takes 94 | map' :: (Sequence a1 -> Sequence a2) -> Sequence a1 -> Sequence a2 95 | map' f (Atom x y) = f (Atom x y) 96 | map' f (Gap x) = f (Gap x) 97 | map' f (Sequence x) = Sequence $ map (map' f) x 98 | map' f (Stack y) = Stack (map (map' f) y) 99 | 100 | -- | Function to map a seqeuence of a functions on another sequence 101 | mapSeq::Sequence (Sequence a-> Sequence b) -> Sequence a -> Sequence b 102 | mapSeq (Atom x f) something = 103 | let (p,q) = forTwo (Atom x f) something 104 | c = reAlign p q 105 | d = unwrap $ Sequence $ map (map' f) c 106 | in d 107 | mapSeq (Gap x) something = 108 | let (p,_) = forTwo (Gap x) something 109 | in unwrap $ Sequence p 110 | mapSeq (Sequence f) something = 111 | let (p,q) = forTwo (Sequence f) something 112 | c = unwrapper $ reAlign p q 113 | d = unwrap $ Sequence $ funcSeq p c 114 | in d 115 | mapSeq (Stack f) something = 116 | let d = map (`mapSeq` something) f 117 | in Stack d 118 | 119 | -- | Takes sequence of functions on sequences and a sequence which have been aligned and applies the functions at 120 | -- the corresponding time points 121 | funcSeq :: [Sequence (Sequence a1 -> Sequence a2)]-> [Sequence a1] -> [Sequence a2] 122 | funcSeq [] _ = [] 123 | funcSeq ((Atom x f):xs) y = 124 | let t = seqSpan (Atom x f) 125 | p = takeWhile (\r -> sum(map seqSpan r) <= t) $ inits y 126 | pTill = last p 127 | q = map (map' f) pTill 128 | in q ++ funcSeq xs (drop (length pTill) y) 129 | funcSeq (Gap x:xs) y= 130 | let t = seqSpan (Gap x) 131 | p = takeWhile (\r -> sum(map seqSpan r) <= t) $ inits y 132 | pTill = last p 133 | q = Gap (sum $ map seqSpan pTill) 134 | in q : funcSeq xs (drop (length pTill) y) 135 | funcSeq (Sequence x:xs) y = funcSeq (unwrapper x ++ xs) y 136 | funcSeq _ _ = error "funcSeq cannot be called on Stack" 137 | 138 | -- | Takes two sequences, which have been obtained using stratApply, or forTwo, and then splits the second sequence with respect 139 | -- to the break points of the first 140 | reAlign:: [Sequence a] -> [Sequence b] -> [Sequence b] 141 | reAlign [] _ = [] 142 | reAlign ((Gap x):xs) y = 143 | let t = seqSpan (Gap x) 144 | p = takeWhile (\q -> sum (map seqSpan q) <=t ) $ inits y 145 | pTill = last p 146 | l = length pTill 147 | tTill = sum (map seqSpan pTill) 148 | (a,b) = if tTill == t then (Gap 0, drop l y) else 149 | let (m,n) = getPartition (y!!l) (t - tTill) 150 | in (m, n :drop (l+1) y) 151 | in if tTill == t then pTill ++ reAlign xs b else (pTill ++ [a]) ++ reAlign xs b 152 | reAlign ((Atom x s):xs) y = 153 | let t = seqSpan (Atom x s) 154 | p = takeWhile (\q -> sum (map seqSpan q) <=t ) $ inits y 155 | pTill = last p 156 | l = length pTill 157 | tTill = sum (map seqSpan pTill) 158 | (a,b) = if tTill == t then (Gap 0, drop l y) else 159 | let (m,n) = getPartition (y!!l) (t - tTill) 160 | in (m, n :drop (l+1) y) 161 | in (pTill ++ [a]) ++ reAlign xs b 162 | reAlign (Sequence x:xs) (Sequence y:ys) = reAlign (unwrapper x ++ xs) (unwrapper y ++ ys) 163 | reAlign _ _ = error "reAlign not defined" 164 | 165 | 166 | -- | Function to partition an event in a sequence 167 | getPartition::Sequence a-> Rational -> (Sequence a, Sequence a) 168 | getPartition (Atom x s) t = (Atom t s, Atom (x-t) s) 169 | getPartition (Gap x) t = (Gap t, Gap (x - t)) 170 | getPartition (Sequence y) t = 171 | let p = takeWhile (\q -> sum (map seqSpan q) <=t ) $ inits y 172 | pTill = last p 173 | l = length pTill 174 | tTill = sum (map seqSpan pTill) 175 | (a,b) = if tTill == t then (Gap 0, drop l y) else 176 | let (m,n) = getPartition (y!!l) (t - tTill) 177 | in (m, n :drop (l+1) y) 178 | in (Sequence $ pTill ++ [a], Sequence b) 179 | getPartition (Stack s) t = let a = map (`getPartition` t) s in (Stack (map fst a),Stack (map snd a)) 180 | 181 | -- | Given two sequences of different types, this function uses the LCM method to align those two sequences 182 | forTwo :: Sequence a1 -> Sequence a2 -> ([Sequence a1], [Sequence a2]) 183 | forTwo a b = 184 | let p = lcmRational (seqSpan a) (seqSpan b) 185 | in (unwrapper $ replicate (fromIntegral $ numerator $ p/seqSpan a) a, unwrapper $ replicate (fromIntegral $ numerator $ p/seqSpan b) b) 186 | 187 | unwrap::Sequence a -> Sequence a 188 | unwrap (Sequence x) = Sequence $ unwrapper x 189 | unwrap (Stack x) = Stack $ map unwrap x 190 | unwrap s = s 191 | 192 | -- | Unwrapping a sequence referes to removing the redundancies that are present in the code 193 | unwrapper:: [Sequence a] -> [Sequence a] 194 | unwrapper [] = [] 195 | unwrapper [Sequence x] = unwrapper x 196 | unwrapper (Sequence x :xs) = unwrapper x ++ unwrapper xs 197 | unwrapper (Atom x s:xs) = Atom x s : unwrapper xs 198 | unwrapper (Gap x:xs) = if x ==0 then unwrapper xs else Gap x: unwrapper xs 199 | unwrapper (Stack x:xs) = Stack x : unwrapper xs 200 | 201 | rev :: Sequence a -> Sequence a 202 | rev (Sequence bs) = Sequence $ reverse $ map rev bs 203 | rev (Stack bs) = Stack $ map rev bs 204 | rev b = b 205 | 206 | cat :: [Sequence a] -> Sequence a 207 | cat [] = Gap 0 208 | cat [b] = b 209 | cat bs = Sequence bs 210 | 211 | ply :: Sequence Rational -> Sequence a -> Sequence a 212 | ply sr s = mapSeq (applyfToSeq _ply sr) s 213 | 214 | _ply :: Rational -> Sequence a -> Sequence a 215 | _ply n (Atom d v) = Sequence $ reduce $ ((replicate (floor n) $ Atom (d / toRational n) v) ++ [Atom (d - ((floor n)%1) *d /n ) v]) 216 | _ply _ (Gap x) = Gap x 217 | _ply n (Sequence x) = unwrap $ Sequence (map (_ply n) x) 218 | _ply n (Stack x) = Stack (map (_ply n) x) 219 | 220 | seqSpan :: Sequence a -> Rational 221 | seqSpan (Atom s _) = s 222 | seqSpan (Gap s) = s 223 | seqSpan (Sequence bs) = sum $ map seqSpan bs 224 | seqSpan (Stack []) = 0 225 | seqSpan (Stack x) = seqSpan $ head x 226 | 227 | lcmRational :: Rational->Rational-> Rational 228 | lcmRational a b = lcm (f a) (f b) % d 229 | where d = lcm (denominator a) (denominator b) 230 | f x = numerator x * (d `div` denominator x) 231 | 232 | -- | stratApply takes a list of sequences, a strategy, and then aligns all those sequences according to these strategies 233 | stratApply::Strategy -> [Sequence a] ->Sequence a 234 | stratApply _ [] = Gap 0 235 | 236 | stratApply JustifyLeft bs = 237 | let a = maximum $ map seqSpan bs 238 | b = map (\x -> Sequence (x: [Gap (a - seqSpan x)])) bs 239 | in Stack b 240 | 241 | stratApply JustifyRight bs = 242 | let a = maximum $ map seqSpan bs 243 | b = map (\x -> Sequence (Gap (a - seqSpan x) : [x])) bs 244 | in Stack b 245 | 246 | stratApply Centre bs = 247 | let a = maximum $ map seqSpan bs 248 | b = map( \x -> Sequence ([Gap ((a - seqSpan x)/2)] ++ [x] ++ [Gap ((a - seqSpan x)/2)])) bs 249 | in Stack b 250 | 251 | stratApply RepeatLCM bs@(x:xs) = 252 | let a = foldr (lcmRational . seqSpan) (seqSpan x) xs 253 | b = map (\r -> unwrap $ Sequence $ replicate (fromIntegral $ numerator $ a/seqSpan r) x) bs 254 | in Stack b 255 | 256 | stratApply Expand bs = 257 | let a = maximum $ map seqSpan bs 258 | b = map (\x -> expand x $ a/seqSpan x) bs 259 | in Stack b 260 | 261 | stratApply Squeeze bs = 262 | let a = minimum $ map seqSpan bs 263 | b = map (\x -> expand x $ a/seqSpan x) bs 264 | in Stack b 265 | 266 | stratApply JustifyBoth bs = 267 | let a = maximum $ map seqSpan bs 268 | b = map (`expand'` a) bs 269 | in Stack b 270 | 271 | stratApply TruncateMin bs = 272 | let a = minimum $ map seqSpan bs 273 | b = map (`cutShort` a) bs 274 | in Stack b 275 | 276 | stratApply TruncateMax bs = 277 | let a = maximum $ map seqSpan bs 278 | b = map (\x -> unwrap $ Sequence $ replicate (floor $ a/seqSpan x) x ++ let Sequence p = cutShort x (realToFrac (a - floor (a/seqSpan x)%1 * seqSpan x)) in p) bs 279 | in Stack b 280 | 281 | -- Return a segment of a sequence 282 | cutShort::Sequence a->Rational->Sequence a 283 | cutShort (Atom x s) r = if x>r then Atom r s else Atom x s 284 | cutShort (Gap x) r = if x > r then Gap r else Gap x 285 | cutShort (Sequence x) r = 286 | let p = takeWhile (\q -> sum (map seqSpan q) <=r ) $ inits x 287 | pTill = last p 288 | l = length pTill 289 | tTill = sum (map seqSpan pTill) 290 | in if tTill == r then Sequence pTill else Sequence $ pTill ++ [fst (getPartition (x!!l) (r - tTill))] 291 | cutShort (Stack x) r = Stack $ map (`cutShort` r) x 292 | 293 | -- | Expand a sequence to a particular length, while not modifying the length of that sequence 294 | expand'::Sequence a -> Rational -> Sequence a 295 | expand' (Atom x s) r = expand (Atom x s) $ r/seqSpan (Atom x s) 296 | expand' (Gap x) r = expand (Gap x) $ r/seqSpan (Gap x) 297 | expand' (Sequence [x]) r = Sequence [expand x (r/seqSpan x)] 298 | expand' (Sequence x) r = 299 | let Sequence y = (expand (Sequence $ init x) $ (r- seqSpan (last x))/ seqSpan (Sequence $ init x)) 300 | in Sequence (y++ [last x]) 301 | expand' (Stack x) r = Stack $ map (`expand'` r) x 302 | 303 | -- | Expand a sequence to a particular length 304 | expand::Sequence a-> Rational -> Sequence a 305 | expand (Atom x s) r = Atom (x*r) s 306 | expand (Gap x) r = Gap (x*r) 307 | expand (Sequence x) r = Sequence $ map (`expand` r) x 308 | expand (Stack x) r = Stack $ map (`expand` r) x 309 | 310 | 311 | -- | Reduce a list of sequences by removing redundancies 312 | reduce::[Sequence a] -> [Sequence a] 313 | reduce (Atom 0 _:xs) = reduce xs 314 | reduce (Gap x1:Gap x2:xs) =reduce $ Gap (x1+x2):xs 315 | reduce (Sequence x:xs) = Sequence (reduce x):reduce xs 316 | reduce (Stack x:xs) = Stack (reduce x):reduce xs 317 | reduce (x:xs) = x:reduce xs 318 | reduce [] = [] 319 | 320 | -- | Applies a function to within a sequence 321 | -- TODO: Is this fmap? 322 | applyfToSeq :: (t -> a) -> Sequence t -> Sequence a 323 | applyfToSeq f (Atom x s) = Atom x (f s) 324 | applyfToSeq _ (Gap x) = Gap x 325 | applyfToSeq f (Sequence x) = Sequence $ map (applyfToSeq f) x 326 | applyfToSeq f (Stack x) = Stack $ map (applyfToSeq f) x 327 | 328 | -- | Speed up the sequence 329 | fast :: Sequence Rational -> Sequence a -> Sequence a 330 | fast sr s = mapSeq (applyfToSeq _fast sr) s 331 | 332 | _seqFast :: Rational -> Sequence a -> Sequence a 333 | _seqFast n (Atom x s) = Atom (x/n) s 334 | _seqFast n (Gap x) = Gap (x/n) 335 | _seqFast n (Sequence s) = Sequence $ map (_fast n) s 336 | _seqFast n (Stack x) = Stack $ map(_fast n) x 337 | 338 | -- | Slow down the sequence 339 | -- slow :: Sequence Rational->Sequence a->Sequence a 340 | -- slow sr s = mapSeq (applyfToSeq _slow sr) s 341 | 342 | -- | Repeat the sequence a desired number of times without changing duration 343 | rep::Int -> Sequence a-> Sequence a 344 | rep n (Atom x s) = Atom (realToFrac n * x) s 345 | rep n (Gap x) = Gap (realToFrac n*x) 346 | rep n (Sequence s) = Sequence $ reduce $ concat $ replicate n s 347 | rep n (Stack s) = Stack $ map (rep n) s 348 | 349 | -- | Repeat sequence desired number of times, and squeeze it into the duration of the original sequence 350 | repSqueeze::Int -> Sequence a-> Sequence a 351 | repSqueeze n s = _fast (realToFrac n) $ rep n s 352 | 353 | -- | Takes a list of sequences, and if aligned returns a stack. Otherwise applies default method and returns 354 | seqStack :: [Sequence a] -> Sequence a 355 | seqStack s = 356 | let a = foldl (\acc x->if seqSpan x==acc then acc else -1) (seqSpan $ head s) s 357 | in if a == (-1) then stratApply Expand s else Stack s 358 | 359 | -- euclid :: Sequence Int -> Sequence Int -> Sequence b -> Sequence b 360 | -- euclid s1 s2 sa = 361 | -- let b = fmap _euclid s1 362 | -- c = b <*> s2 363 | -- d = mapSeq c sa 364 | -- in d 365 | 366 | -- -- | Obtain a euclidean pattern 367 | -- _euclid:: Int-> Int-> Sequence a -> Sequence a 368 | -- _euclid a b s = 369 | -- let x = bjorklund (a, b) 370 | -- y = map (\t -> if t then s else Gap (seqSpan s)) x 371 | -- in unwrap $ Sequence y 372 | 373 | every :: Sequence Int -> (Sequence b -> Sequence b) -> Sequence b -> Sequence b 374 | every si f sa = mapSeq (applyfToSeq (every' f) si) sa 375 | 376 | every' :: (Sequence a -> Sequence a) -> Int -> Sequence a -> Sequence a 377 | every' f s = _every s f 378 | 379 | _every :: Int -> (Sequence a -> Sequence a) -> Sequence a -> Sequence a 380 | _every n f s = unwrap $ Sequence $ replicate (n-1) s ++ [f s] 381 | 382 | 383 | 384 | -- makeSeq:: [Syllable] -> Rational -> Sequence Syllable 385 | -- makeSeq x r = 386 | -- let a = lcmRational (realToFrac $ length x) r 387 | 388 | -- b = concat $ replicate (div (fromIntegral $ numerator a) (length x)) x 389 | -- c = map (\t -> if t == Gdot then Gap (1/r) else Atom (1/r) t) b 390 | -- in unwrap $ Sequence c 391 | 392 | fromList:: [a] -> Sequence a 393 | fromList x= unwrap $ Sequence $ reduce $ map (Atom 1) x 394 | 395 | fastFromList ::[a] -> Sequence a 396 | fastFromList x = unwrap $ Sequence $ reduce $ map (Atom (realToFrac $ (1%length x))) x 397 | 398 | listToPat ::[a] -> Sequence a 399 | listToPat = fastFromList 400 | 401 | seqFastcat :: [Sequence a] -> Sequence a 402 | seqFastcat x = _fast (sum $ map seqSpan x) $ Sequence (reduce x) 403 | 404 | fromMaybes :: [Maybe a] -> Sequence a 405 | fromMaybes = fastcat . map f 406 | where f Nothing = Gap 1 407 | f (Just x) = Atom 1 x 408 | 409 | run :: (Enum a, Num a) => Sequence a -> Sequence a 410 | run x = unwrap $ (>>= _run) x 411 | 412 | _run :: (Enum a, Num a) => a -> Sequence a 413 | _run n = unwrap $ fastFromList [0 .. n-1] 414 | 415 | seqSlowcat :: [Sequence a] -> Sequence a 416 | seqSlowcat [] = Gap 0 417 | seqSlowcat [b] = b 418 | seqSlowcat bs = Sequence bs 419 | 420 | -- | From @1@ for the first cycle, successively adds a number until it gets up to @n@ 421 | scan :: (Enum a, Num a) => Sequence a -> Sequence a 422 | scan x = unwrap $ (>>= _scan) x 423 | 424 | _scan :: (Enum a, Num a) => a -> Sequence a 425 | _scan n = unwrap $ slowcat $ map _run [1 .. n] 426 | 427 | -- | Alias for 'append' 428 | slowAppend :: Sequence a -> Sequence a -> Sequence a 429 | slowAppend = append 430 | slowappend :: Sequence a -> Sequence a -> Sequence a 431 | slowappend = append 432 | 433 | -- | Like 'append', but twice as fast 434 | fastAppend :: Sequence a -> Sequence a -> Sequence a 435 | fastAppend a b = _fast 2 $ append a b 436 | fastappend :: Sequence a -> Sequence a -> Sequence a 437 | fastappend = fastAppend 438 | 439 | timeCat :: [(Rational, Sequence a)] -> Sequence a 440 | timeCat x = cat $ map (\t -> _fast (seqSpan (snd t)/fst t) (snd t)) x 441 | 442 | -- | Alias for @timeCat@ 443 | timecat :: [(Rational, Sequence a)] -> Sequence a 444 | timecat = timeCat 445 | 446 | -- | An alias for @fast@ 447 | density :: Sequence Rational -> Sequence a -> Sequence a 448 | density = fast 449 | 450 | rotL :: Rational -> Sequence a -> Sequence a 451 | rotL t (Sequence x) = splitUp t x 452 | rotL t (Stack x) = Stack $ map (t `rotL`) x 453 | rotL _ x = x 454 | 455 | rotR :: Rational -> Sequence a -> Sequence a 456 | rotR t (Sequence x) = splitUp (seqSpan (Sequence x) - t) x 457 | rotR t (Stack x) = Stack $ map (t `rotR`) x 458 | rotR _ x = x 459 | 460 | splitUp :: Rational -> [Sequence a] -> Sequence a 461 | splitUp t x = 462 | let a = takeWhile (\m -> sum (map seqSpan m) <=t ) (inits x) 463 | pTill =if null a then [] else last a 464 | l = length pTill 465 | tTill = sum (map seqSpan pTill) 466 | (p,q) = if tTill == t then (pTill, drop l x) else 467 | let (m,n) = getPartition (x!!l) (t - tTill) 468 | in (pTill ++ [m], n : drop (l+1) x) 469 | in Sequence $ q++p 470 | 471 | -- -- | Shifts a sequence back in time by the given amount, expressed in cycles 472 | -- (<~) :: Sequence Rational -> Sequence a -> Sequence a 473 | -- (<~) sr s= mapSeq (applyfToSeq rotL sr) s 474 | 475 | -- -- | Shifts a pattern forward in time by the given amount, expressed in cycles 476 | -- (~>) :: Sequence Rational -> Sequence a -> Sequence a 477 | -- (~>) sr s = mapSeq (applyfToSeq rotR sr) s 478 | 479 | iter :: Sequence Int -> Sequence a -> Sequence a 480 | iter sr s = 481 | let (a,b) = forTwo sr s 482 | in unwrap $ iterer (Sequence a) (Sequence b) 483 | 484 | iterer :: Sequence Int -> Sequence a -> Sequence a 485 | iterer (Atom _ s) sr = _iter s sr 486 | iterer (Gap x) _ = Gap x 487 | iterer (Sequence x) sr = Sequence $ map (\t -> iterer t sr) x 488 | iterer (Stack x) sr = stack $ map (\t -> iterer t sr) x 489 | 490 | _iter :: Int -> Sequence a -> Sequence a 491 | _iter n p = slowcat $ map (\i -> ((fromIntegral i) % (fromIntegral n)) `rotL` p) [0 .. (n-1)] 492 | 493 | -- | @iter'@ is the same as @iter@, but decrements the starting 494 | -- subdivision instead of incrementing it. 495 | iter' :: Sequence Int -> Sequence c ->Sequence c 496 | iter' sr s= 497 | let (a,b) = forTwo sr s 498 | in unwrap $ iterer' (Sequence a) (Sequence b) 499 | 500 | iterer' :: Sequence Int -> Sequence a -> Sequence a 501 | iterer' (Atom _ s) sr = _iter' s sr 502 | iterer' (Gap x) _ = Gap x 503 | iterer' (Sequence x) sr = Sequence $ map (\t -> iterer' t sr) x 504 | iterer' (Stack x) sr = stack $ map (\t -> iterer' t sr) x 505 | 506 | 507 | _iter' :: Int -> Sequence a -> Sequence a 508 | _iter' n p = slowcat $ map (\i -> (fromIntegral i % fromIntegral n) `rotR` p) [0 .. (n-1)] 509 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------