变量不在嵌套的范围内

时间:2017-11-20 12:53:34

标签: haskell

我实现了luhn算法,这是我到目前为止的代码:

luhn :: [Int] -> Bool
luhn xs = ((evens + odds) `mod` 10) == 0 where
      evens = sum [x | (x,i) <- reversed_indexed_xs, i `mod` 2 == 0]
      odds = sum [luhnDouble x | (x,i) <- reversed_indexed_xs, i `mod` 2 /= 0] where
            reversed_indexed_xs = zip (reverse xs) [0..]

错误我得到了

 Variable not in scope: reversed_indexed_xs :: [(a, Integer)]
   |
33 |       evens = sum [x | (x,i) <- reversed_indexed_xs, i `mod` 2 == 0]
   |                                 ^^^^^^^^^^^^^^^^^^^
Failed, 0 modules loaded.

尽管在嵌套的reversed_indexed_xs语句中定义了where。 我认为我的问题是缩进,有什么帮助吗?

3 个答案:

答案 0 :(得分:8)

您不需要另一个嵌套where,只需执行

luhn :: [Int] -> Bool
luhn xs = ((evens + odds) `mod` 10) == 0 where
      evens = sum [x | (x,i) <- reversed_indexed_xs, i `mod` 2 == 0]
      odds = sum [luhnDouble x | (x,i) <- reversed_indexed_xs, i `mod` 2 /= 0]
      reversed_indexed_xs = zip (reverse xs) [0..]

问题在于,当您编写X where Y时,Y中的定义只能在表达式X中使用。在您的情况下,reversed_indexed_xs只能在odds的定义范围内使用。

答案 1 :(得分:7)

您使用where语句确定了odds,而不是even

luhn :: [Int] -> Bool
luhn xs = ((evens + odds) `mod` 10) == 0 where
      evens = sum [x | (x,i) <- reversed_indexed_xs, i `mod` 2 == 0]
      odds = sum [luhnDouble x | (x,i) <- reversed_indexed_xs, i `mod` 2 /= 0] where
            reversed_indexed_xs = zip (reverse xs) [0..]

由于reversed_indexed_xs不使用与odds绑定的变量,因此我们只需将其与evensodds放在同一级别:

luhn :: [Int] -> Bool
luhn xs = ((evens + odds) `mod` 10) == 0 where
      evens = sum [x | (x,i) <- reversed_indexed_xs, i `mod` 2 == 0]
      odds = sum [luhnDouble x | (x,i) <- reversed_indexed_xs, i `mod` 2 /= 0]
      reversed_indexed_xs = zip (reverse xs) [0..]

答案 2 :(得分:7)

嵌套where的范围仅限于它嵌套的定义 - 即odds, - 但您在evensodds中使用它odds。它位于evens的范围内,但不适用于evens

要在oddsluhn :: [Int] -> Bool luhn xs = ((evens + odds) `mod` 10) == 0 where evens = sum [x | (x,i) <- reversed_indexed_xs, i `mod` 2 == 0] odds = sum [luhnDouble x | (x,i) <- reversed_indexed_xs, i `mod` 2 /= 0] reversed_indexed_xs = zip (reverse xs) [0..] 中使用它,您只需在同一级别定义它,不需要嵌套:

export default graphql(ALL_INSPECTIONS_QUERY, { name: 'allInspectionsQuery' })(InspectionRow)

export { InspectionTable }