我正在阅读应用函数的实例, 并遇到一行
def yearsToTrack():
userYearsTracking = int(input("How many years do you want to track: "))
return userYearsTracking
def calculationAlgorithm(userYearsTracking):
totalMonths = 0
totalRainfall = 0
for currentYear in range (1, userYearsTracking +1):
for currentMonth in range (1, 13):
monthlyRainfall = int(input("Inches of rainfall for month " + format(currentMonth, "d",) + " | year " +
format(currentYear, "d",)+": "))
totalMonths += 1
totalRainfall += monthlyRainfall
averageRainfall = totalRainfall / totalMonths
print("Total months: " + str(totalMonths))
print("Total rain:", format(totalRainfall), "(inch)")
print("Total average rainfall:", round(averageRainfall,2), "(inch)")
def main():
userYearsTracking = yearsToTrack()
calculationAlgorithm(userYearsTracking)
main()
我理解语法,但不理解第二行的含义。
我的理解是:部分应用函数instance Applicative ((->) r) where
pure x = (\_ -> x)
f <*> g = \x -> f x (g x)
获取一个值并将该值包装到上下文中,该上下文包含始终返回该值的函数。
为什么不通过将部分应用的函数应用于((->) r)
来计算结果,只有在此之后它才会将结果存储在Applicative上下文中?
答案 0 :(得分:8)
函数实例的pure
和(<*>)
的签名是
pure :: a -> ((->) r a)
(<*>) :: ((->) r (a -> b)) -> ((->) r a) -> ((->) r b)
将( - &gt;)写为中缀运算符
pure :: a -> (r -> a)
(<*>) :: (r -> (a -> b)) -> (r -> a) -> (r -> a)
因此pure
是一个函数,它接受类型为a
的参数,并返回一个带有r
类型参数的函数,并返回类型为a
的值。
由于我们在编写r
时无法知道pure
的类型,因此我们只能提供一个函数来返回给予pure
的参数。