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
let go (x, y) =
let r = (y - x) / 3
go (x, y) = [(x, x + r), (y - r, y)]
where
in [(x, x + r), (y - r, y)]
in iterate (>>= go) . return
r = (y - x) / 3


---------------------------- TEST --------------------------
main :: IO ()
main :: IO ()
main = do
main = do
Line 933: Line 934:
putStrLn $ intervalBars xs
putStrLn $ intervalBars xs


-- DISPLAY FUNCTIONS ---------------------------------------------------
-------------------------- DISPLAY -------------------------
intervalBars :: [[(Rational, Rational)]] -> String
intervalBars :: [[(Rational, Rational)]] -> String
intervalBars xs =
intervalBars xs = unlines $ go (d % 1) <$> xs
where
let go w xs =
concat . snd $
d = maximum $ denominator . fst <$> last xs
mapAccumL
go w xs =
(\a (rx, ry) ->
concat . snd $
mapAccumL
let (wx, wy) = (w * rx, w * ry)
(\a (rx, ry) ->
in ( wy -- Accumulator – end of previous interval.
, replicate (floor (wx - a)) ' ' -- Preceding gap, and
let (wx, wy) = (w * rx, w * ry)
++
in ( wy -- Accumulator end of previous interval.
replicate (floor (wy - wx)) '' -- interval bar.
, replicate (floor (wx - a)) ' ' -- Preceding gap, and
))
++
replicate (floor (wy - wx)) '█' -- interval bar.
0
xs
))
0
d = maximum $ (denominator . fst) <$> last xs
in unlines $ go (d % 1) <$> xs
xs


intervalRatios :: [(Rational, Rational)] -> String
intervalRatios :: [(Rational, Rational)] -> String
intervalRatios xs =
intervalRatios = ('(' :) . (++ ")") . intercalate ") (" . fmap go
where
let go (rx, ry) = intercalate ", " $ showRatio <$> [rx, ry]
in '(' : intercalate ") (" (go <$> xs) ++ ")"
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
go x
in show (numerator r) ++ bool [] ('/' : show d) (1 /= d)</lang>
| 1 /= x = '/' : show x
| otherwise = []</lang>
{{Out}}
{{Out}}
<pre>(0, 1)
<pre>(0, 1)