如何构建Haskell'#'山?

发布于 2025-02-07 05:03:55 字数 358 浏览 0 评论 0原文

定义了一种称为山的功能,该功能吸引了一个高度n和宽度,可以从东部(右)攀登。每行将山从上到下扩大一个字符。这座山应该由“#”角色组成,山的不同层次被Newline角色隔开。在山尽头没有新的line角色。高度为负的山的高度应等于0,因此在这种情况下,结果应为空列表。

您是否知道我在其他情况下可以写什么?

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

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 = ???

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

画骨成沙 2025-02-14 05:03:55

您可以使用累加器:一个包含字符的数量的变量,然后对这些项目进行递归调用。

然后,Mountain功能看起来像:

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

您需要填写零件。

一种更优雅的方法可能是使用map在其中我们从1 n 创建列表,以及该行的字符串上的每个时间映射,然后使用字符串] - &gt;字符串 将这些字符串加在一起:

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

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])
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文