如果我在Haskell中运行此代码,究竟是以什么顺序计算的?

时间:2018-02-20 08:51:15

标签: ghci winghci

我在这website

上编写了这段代码
  

输入:foldr(/)2 [8,12,24,4]

     

输出:8.0

如何计算此输出?

  

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

1 个答案:

答案 0 :(得分:0)

哦,Stack Overflow不允许简短的回答。好的,一个简短的解释是有序的(虽然我认为你已经明白了)。

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 从右到左应用于列表的每个元素,如下所示:

/

或者在中缀函数的情况下(例如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

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

import re

myvar = False
with open('Sample Test.txt') as f:
    for line in f:
        if re.search(r'index1', line):
            myvar = True
            print (line)

        elif re.search(r'index2', line):
            myvar = False
            print (line)

        elif myvar:
            print(line)
            continue

这正是您所描述的。