gpt4 book ai didi

haskell - 你能帮我理解这段代码是如何工作的吗我是haskell的新手

转载 作者:行者123 更新时间:2023-12-02 03:28:44 27 4
gpt4 key购买 nike

我正在查找一些带有答案的 Haskell 练习。这是练习:

Assume that you have a function rainfall which computes the rainfall in your city for a given week (where weeks are numbered from 1 and upwards)

type WeekNumber = Int
rainfall :: WeekNumber -> Double -- assume this function exists

Complete the definition of the following function:

mostRain :: WeekNumber -> Double
mostRain n | n < 1 = 0
| otherwise = -- (complete this case)

Your solution must be recursive. Hint: The function max may be useful. Note that you do not have to provide a definition for the function rainfall.

答案:

import Data.List
import Data.Maybe
import Test.QuickCheck
-- 1 ----------------
type WeekNumber = Int
rainfall :: WeekNumber -> Double
rainfall n = fromIntegral (n `mod` 7) * 3.9

mostRain :: WeekNumber -> Double
mostRain n | n < 1 = 0
| otherwise = rainfall n `max` mostRain (n - 1)

我真的希望有人能帮我解释一下他们是如何得出这个数字 3.9 (n `mod` 7) * 3.9

这里实际发生了什么否则=降雨量n`max`mostRain(n - 1)

最佳答案

首先,正如 @AJFarmar 指出的那样,写 rainfall函数不是练习的一部分。答案只是提供了一个任意定义,以便您可以测试该解决方案,而数字 3.9 只是凭空拉出来的,以使降雨量看起来“有趣”:

> rainfall 1
3.9
> rainfall 2
7.8
>

你并不需要真正理解这个表达式的含义:

fromIntegral (n `mod` 7) * 3.9

确实理解解决方案,但如果您感兴趣,它需要输入整数 n ,计算n `mod` 7 (这是 n 除以 7 的余数,因此将 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 变成 1, 2, 3, 4, 5, 6, 0 , 1, 2, 3),并将结果从整数转换为 double ,然后再乘以 3.9。例如,这给出了第 1 周到第 10 周的降雨量,如下所示:

> map rainfall [1..10]
[3.9,7.8,11.7,15.6,19.5,23.4,0.0,3.9,7.8,11.7]
>

了解otherwise之后的解决方案部分,首先让我们重写它以摆脱特殊的反引号符号:

mostRain :: WeekNumber -> Double
mostRain n | n < 1 = 0
| otherwise = max (rainfall n) (mostRain (n - 1))

这个定义说的是计算第1周到第n周所见的最多降雨量,即mostRain n ,将被定义为 0如果n < 1否则使用以下表达式:

max (rainfall n) (mostRain (n - 1))

此表达式计算两个数字中的最大值,即 rainfall n 的值(即,n 周的降雨量)和 mostRain (n - 1) 的值。这是一个递归调用,它将计算第 1 周至 n-1 内出现的最多降雨量。 .

因此,这实际上是说,从第 1 周到第 n 周的最多降雨量定义为 (1) 第 n 周的降雨量和 (2) 前几周的最多降雨量中的最大值。或者,您可以将其视为按如下步骤执行计算:

mostRain 3
= max (rainfall 3) (mostRain 2)
= max (rainfall 3) (max (rainfall 2) (mostRain 1))
= max (rainfall 3) (max (rainfall 2) (max (rainfall 1) (mostRain 0))
= max (rainfall 3) (max (rainfall 2) (max (rainfall 1) 0)

如果我们填写模拟降雨量,您可以看到它最终如何计算​​最大值:

= max 11.7 (max 7.8 (max 3.9 0)
= max 11.7 (max 7.8 3.9)
= max 11.7 7.8
= 11.7

关于haskell - 你能帮我理解这段代码是如何工作的吗我是haskell的新手,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52460571/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com