Cantor set: Difference between revisions
Content added Content deleted
m (→{{header|AppleScript}}: tidied. Added preamble.) |
(→Haskell :: Dual representation: Tidied, pruned out one import.) |
||
Line 918: | Line 918: | ||
<lang haskell>import Data.Ratio (Ratio, (%), numerator, denominator) |
<lang haskell>import Data.Ratio (Ratio, (%), numerator, denominator) |
||
import Data.List (intercalate, mapAccumL, maximumBy) |
import Data.List (intercalate, mapAccumL, maximumBy) |
||
import Data.Bool (bool) |
|||
--------------------------- CANTOR ------------------------- |
|||
cantor :: (Rational, Rational) -> [[(Rational, Rational)]] |
cantor :: (Rational, Rational) -> [[(Rational, Rational)]] |
||
cantor = |
cantor = iterate (>>= go) . return |
||
where |
|||
⚫ | |||
go (x, y) = [(x, x + r), (y - r, y)] |
|||
⚫ | |||
⚫ | |||
r = (y - x) / 3 |
|||
---------------------------- TEST -------------------------- |
|||
main :: IO () |
main :: IO () |
||
main = do |
main = do |
||
Line 933: | Line 934: | ||
putStrLn $ intervalBars xs |
putStrLn $ intervalBars xs |
||
-------------------------- DISPLAY ------------------------- |
|||
intervalBars :: [[(Rational, Rational)]] -> String |
intervalBars :: [[(Rational, Rational)]] -> String |
||
intervalBars xs = |
intervalBars xs = unlines $ go (d % 1) <$> xs |
||
where |
|||
let go w xs = |
|||
d = maximum $ denominator . fst <$> last xs |
|||
go w xs = |
|||
concat . snd $ |
|||
mapAccumL |
|||
let (wx, wy) = (w * rx, w * ry) |
|||
⚫ | |||
in ( wy -- Accumulator – end of previous interval. |
|||
let (wx, wy) = (w * rx, w * ry) |
|||
in ( wy -- Accumulator – end of previous interval. |
|||
, replicate (floor (wx - a)) ' ' -- Preceding gap, and |
|||
++ |
|||
replicate (floor (wy - wx)) '█' -- interval bar. |
|||
⚫ | |||
)) |
|||
0 |
|||
d = maximum $ (denominator . fst) <$> last xs |
|||
xs |
|||
intervalRatios :: [(Rational, Rational)] -> String |
intervalRatios :: [(Rational, Rational)] -> String |
||
intervalRatios |
intervalRatios = ('(' :) . (++ ")") . intercalate ") (" . fmap go |
||
where |
|||
let go (rx, ry) = intercalate ", " $ showRatio <$> [rx, ry] |
|||
go (rx, ry) = intercalate ", " $ showRatio <$> [rx, ry] |
|||
showRatio :: Rational -> String |
showRatio :: Rational -> String |
||
showRatio = ((++) . show . numerator) <*> (go . denominator) |
|||
showRatio r = |
|||
where |
|||
let d = denominator r |
|||
⚫ | |||
in show (numerator r) ++ bool [] ('/' : show d) (1 /= d)</lang> |
|||
| 1 /= x = '/' : show x |
|||
| otherwise = []</lang> |
|||
{{Out}} |
{{Out}} |
||
<pre>(0, 1) |
<pre>(0, 1) |