HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Printing an arrow of asterisks in Haskell

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
asterisksprintingarrowhaskell

Problem

This code will print an arrow of asterisks, like:

*
**
***
****
***
**
*


raisingAsterisks, decreasingAsterisks, arrow :: Int -> [String]
raisingAsterisks n = take n $ iterate ('*' :) "*"
decreasingAsterisks = reverse . raisingAsterisks
arrow n = raisingAsterisks n ++ (tail (decreasingAsterisks n))

main :: IO()
main = mapM_ putStrLn $ arrow 4

Solution

The way you're actually generating the list of Strings seems fine, but the formatting, at least in my opinion, can be improved: since raisingAsterisks and decreasingAsterisks are both relatively small "helper" functions for arrow, I would suggest putting them inside a where clause to make things a little easier to read.

arrow :: Int -> [String]
arrow n = increasing ++ tail decreasing
    where increasing = take n $ iterate ('*' :) "*"
          decreasing = reverse increasing


In this context, the variable names could be shortened, due to the fact that it's easy to understand what's happening. Note that the n variable no longer needs to be passed, so increasing and decreasing actually are no longer even functions!

I hope you agree that changing your code just a little greatly improves readability.

Code Snippets

arrow :: Int -> [String]
arrow n = increasing ++ tail decreasing
    where increasing = take n $ iterate ('*' :) "*"
          decreasing = reverse increasing

Context

StackExchange Code Review Q#104598, answer score: 5

Revisions (0)

No revisions yet.