Skip to content

Instantly share code, notes, and snippets.

@ajnsit
Created March 29, 2016 07:06
Show Gist options
  • Save ajnsit/8ec9bf75bf344bfc7a46 to your computer and use it in GitHub Desktop.
Save ajnsit/8ec9bf75bf344bfc7a46 to your computer and use it in GitHub Desktop.
ASCII Spirals in Haskell
type Elem = [String]
width :: Elem -> Int
width e
| (c:_) <- e = length c
| otherwise = 0
height :: Elem -> Int
height = length
above :: Elem -> Elem -> Elem
above c1 c2 = widen w c1 ++ widen w c2
where w = max (width c2) (width c1)
besides :: Elem -> Elem -> Elem
besides c1 c2 = zipWith (++) (heighten h c1) (heighten h c2)
where h = max (height c1) (height c2)
widen :: Int -> Elem -> Elem
widen = map . (\ w l -> take w $ l ++ repeat ' ')
heighten :: Int -> Elem -> Elem
heighten w c = trim $ take w $ c ++ repeat ""
where trim c = widen (width c) c
display :: Elem -> IO ()
display = putStrLn . unlines
spiral :: Int -> Int -> Elem
spiral n dir
| 1 <- n = corner
| otherwise =
case dir of
0 -> (corner `besides` row) `above` (sp `besides` space)
1 -> (sp `above` space) `besides` (corner `above` col)
2 -> (space `besides` sp) `above` (row `besides` corner)
3 -> (col `above` corner) `besides` (space `above` sp)
where
sp = spiral (n-1) ((dir + 3) `rem` 4)
row = [replicate (width sp) '-']
col = replicate (width sp) ['|']
space = [" "]
corner = ["+"]
main = display $ spiral 10 0
@ajnsit
Copy link
Author

ajnsit commented Mar 29, 2016

Sample output -

+---------
|         
| +-----+ 
| |     | 
| | +-+ | 
| | + | | 
| |   | | 
| +---+ | 
|       | 
+-------+ 

@ajnsit
Copy link
Author

ajnsit commented Mar 29, 2016

Rewriting the _terrible_ code example from the official Scala book! - https://www.cs.helsinki.fi/u/wikla/OTS/Sisalto/examples/html/ch10.html#sec14

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment