簡體   English   中英

如果我在Haskell中運行此代碼,究竟按什么順序計算?

[英]What exactly is being calculated in which order if i run this code in Haskell?

我在這個網站上看到了這段代碼:

輸入:文件夾(/)2 [8,12,24,4]

輸出:8.0

如何計算此輸出?

是8 /(12 /(24 /(4/2)))= 8.0嗎?

是。

哦,堆棧溢出不允許簡短的答案。 好的,接下來是一個簡短的解釋(盡管我認為您已經理解了)。

foldr定義為:

foldr :: (a -> b -> b) -> b -> [a] -> b

用簡單和更具描述性的術語:

foldr :: function_to_apply -> accumulator_start_value -> list -> accumulator_end_value

其中function_to_apply從右到左應用於列表的每個元素,如下所示:

next_accumulator_value = function_to_apply current_element current_accumulator_value

或使用infix函數(例如/運算符):

next_accumulator_value = current_element `function_to_apply` current_accumulator_value

請注意,表達式中的(/)僅表示:

(\current_element current_accumulator_value -> current_element / current_accumulator_value)

因此,您的示例的計算如下:

foldr (/) 2 [8,12,24,4]  -- ( 4 2 -> 4/2 )
foldr (/) (4/2) [8,12,24]  -- ( 24 (4/2) -> 24/(4/2) )
foldr (/) (24/(4/2)) [8,12]  -- ( 12 (24/(4/2)) -> 12/(24/(4/2)) )
foldr (/) (12/(24/(4/2))) [8]  -- ( 8 (12/(24/(4/2))) -> 8/(12/(24/(4/2))) )
foldr (/) (8/(12/(24/(4/2)))) []  -- nothing to apply to any more, the accumulated expression can now be evaluated

正是您所描述的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM