patternMinor
Printing patterns in Haskell
Viewed 0 times
printingpatternshaskell
Problem
Write a function
For example:
This idea is inspired by Writing nested for loops to produce certain output (but more general).
I am pretty satisfied with my code to solve this problem:
Int -> Char -> Char -> [String] that will create the appropriate pattern.For example:
mapM_ putStrLn (pattern 48 '.' '+')................................................
.+..+..+..+..+..+..+..+..+..+..+..+..+..+..+..+.
+.++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.+
................................................
This idea is inspired by Writing nested for loops to produce certain output (but more general).
I am pretty satisfied with my code to solve this problem:
pattern :: Int -> Char -> Char -> [String]
pattern len a b = map (take len . cycle) [[a], [a, b, a], [b, a, b], [a]]
main :: IO()
main = mapM_ putStrLn (pattern 48 '.' '+')
Solution
Seems fine. However, depending on the context and the rest of the program, you can relax
Also, since every
pattern's type:pattern :: Int -> a -> a -> [[a]]Also, since every
putStrLn is basically hPutStrLn stdout, you could first glue all lines together with unlines and then print them with a single action:main = putStr (unlines (pattern 48 '.' '+'))Code Snippets
pattern :: Int -> a -> a -> [[a]]main = putStr (unlines (pattern 48 '.' '+'))Context
StackExchange Code Review Q#111961, answer score: 5
Revisions (0)
No revisions yet.