Last active
December 12, 2015 02:28
-
-
Save sshine/4698954 to your computer and use it in GitHub Desktop.
A simple Haskell program for generating Brainfuck-code that prints strings. Append "[.>]" to print.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module BFName where | |
import Data.Char | |
import Data.List | |
makeName :: String -> String | |
makeName = makeBase | |
(***) :: String -> Int -> String | |
s *** n = concat (replicate n s) | |
diff :: Int -> Int -> String | |
diff from to = replicate (abs n) c | |
where | |
n = from - to | |
c = if n > 0 then '-' else '+' | |
-- Assumes that a[cur] = 0 | |
makeChar :: Char -> String | |
makeChar c = | |
-- "++++++++[>++++++++<-]>" ++ diff 64 n | |
incr ++ "[>" ++ incr ++ "<-]>" ++ rest | |
where | |
n = ord c | |
sq = truncate (sqrt $ fromIntegral n) | |
incr = "+" *** sq | |
rest = "+" *** (n - sq*sq) | |
makeBase :: String -> String | |
makeBase name = | |
charCode ++ replicateCode ++ adjustCode | |
where | |
charCode = makeChar (chr avg) | |
replicateCode = "[" ++ ">+" *** len | |
-- ++ "<" *** len ++ "-]" | |
++ "[<]>-]" | |
adjustCode = concatMap (\n -> ">" ++ (diff avg n)) ints | |
-- ++ "<" *** len | |
++ "[<]>" | |
len = length name | |
ints = map ord name | |
avg = roundedAvg ints | |
roundedAvg :: [Int] -> Int | |
roundedAvg ns = | |
if length ns == 0 then 0 else sum ns `div` length ns |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment