我实现了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
。
我认为我的问题是缩进,有什么帮助吗?
答案 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
绑定的变量,因此我们只需将其与evens
和odds
放在同一级别:
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
, - 但您在evens
和odds
中使用它odds
。它位于evens
的范围内,但不适用于evens
。
要在odds
和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..]
中使用它,您只需在同一级别定义它,不需要嵌套:
export default graphql(ALL_INSPECTIONS_QUERY, { name: 'allInspectionsQuery' })(InspectionRow)
export { InspectionTable }