[英]Haskell function that evaluates f 0 + f 1 + … + f n without explicit recursion
我設計了一個 function 'total' total:: (Integer -> Integer) -> (Integer -> Integer)
這樣總 f 就是 function ,它的值 n 給出了總 f 0 + f 1 + … + fn 使用在 Haskell 函數中,而不是顯式遞歸。
Now, my first instinct was to use the map function to apply said function to a list of Integers [1..n], then use the sum function in order to calculate this, but it is erroring out on me and giving this message:
code.hs:8:17: error:
• Couldn't match type ‘[b0]’ with ‘[Integer] -> Integer’
Expected type: (a0 -> b0)
-> (Integer -> Integer) -> [Integer] -> Integer
Actual type: (a0 -> b0) -> [a0] -> [b0]
• In the first argument of ‘sum’, namely ‘map’
In the expression: sum map (f) [1 .. n]
In an equation for ‘total’: total f n = sum map (f) [1 .. n]
|
8 | total f n = sum map (f) [1..n]
| ^^^
這是我寫的代碼:
total :: (Integer -> Integer) -> (Integer -> Integer)
total f n = sum map (f) [1..n]
現在我明白錯誤在說什么(我需要遵循 function 聲明),但我很困惑為什么 Haskell 不解釋第二部分周圍的括號,以及我應該如何在沒有列表和映射 function。 也許使用 Lambda 抽象? 我不知道。 我應該如何解決這個問題?
您將map
作為參數傳遞給sum
,而不是調用map
的結果。
total f n = sum (map f [1..n])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.