Home > Software engineering >  How can I build a haskell '#' mountain?
How can I build a haskell '#' mountain?

Time:06-14

Define a function called mountain that draws a mountain of height n and width that can be climbed from the east (right). Widen the mountain from top to bottom by one character per line. The mountain should consist of '#' characters, with the different levels of the mountain separated by the newline character. No more new line characters at the end of the mountain. A mountain with a negative height should be equal to a height of 0, so in this case the result should be an empty list.

Do you have any idea what I could write in the otherwise case ?

mountain :: Int -> String
mountain a 
 | a < 1 = ""
 | a == 1 = "#"
 | a == 2 == "#\n##"
 | otherwise = ???

CodePudding user response:

You can work with an accumulator: a variable that contains the number of # characters you need to write, and then makes a recursive call for these items.

The mountain function then looks like:

mountain :: Int -> String
mountain n = go 1
    where go i 
              |  i <= n = …    go (i 1)
              | otherwise = …

where you need to fill in the parts.

A more elegant approach might be to use map where we create a list from 1 to n, and each time map on a string for that line, and then use unlines :: [String] -> String to join these strings together:

mountain :: Int -> String
mountain = unlines (map (…) [1 .. n])
  • Related