如何检查列表元素的总和是否等于 Haskell 中的最后一个元素?
How to check if sum of list elements are equal to the last element in Haskell?
输入是一个包含 9 个元素的列表。
我想检查前 8 个元素的 sum/10 的余数(使用下面的算法,taj 的第二行)是否等于最后一个(第 9 个)元素。
目前我的程序计算余数,但我不知道如何检查它。我尝试了几种方法。
oddS :: Int-> Int
oddS x = x*3
evenS :: Int -> Int
evenS y = y*7
taj :: [Int] -> Int
taj (a:b:c:d:e:f:g:h:w) = (oddS a + evenS b + oddS c + evenS d + oddS e + evenS f + oddS g + evenS h) `mod` 10
我知道这不是最好的解决方案,但它确实可以。
Willem 帮助下的替代解决方案。
check :: [Int] -> Bool
check xs = xn == taj xs
where xn = last xs
I would like to check if the first 8 elements's sum/10's remainder is equal to the last (9th) element.
it's a validation algorithm. It works like that. The input list is valid if the first 8 elements's (the sum of odd indexed elements*3 and even indexed elements*7) mod 10 equals to the last element. - comment
您还可以使用 递归 来检查条件,方法是使用累加运行 sum 并在到达最后一个元素时检查它。所以像:
check9 :: [Int] -> Bool
check9 = check9' 8 0
where check9' n s [xn] = n == 0 && s `mod` 10 == xn
check9' n s (x:x2:xs) = check9' (n-2) (s+3*x+7*x2) xs
check9' _ _ _ = False
解决这个问题的更优雅的方法是使用 sum :: Num a => [a] -> a
、zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
、cycle :: [a] -> [a]
和 splitAt :: [a] -> a
:
等内置函数
<b>-- alternative version</b>
check9 :: [Int] -> Bool
check9 xs | (xi,[xn]) <- splitAt 8 xs = xn == mod (sum (zipWith (*) xi $ cycle [3,7])) 10
| otherwise = False
输入是一个包含 9 个元素的列表。
我想检查前 8 个元素的 sum/10 的余数(使用下面的算法,taj 的第二行)是否等于最后一个(第 9 个)元素。
目前我的程序计算余数,但我不知道如何检查它。我尝试了几种方法。
oddS :: Int-> Int
oddS x = x*3
evenS :: Int -> Int
evenS y = y*7
taj :: [Int] -> Int
taj (a:b:c:d:e:f:g:h:w) = (oddS a + evenS b + oddS c + evenS d + oddS e + evenS f + oddS g + evenS h) `mod` 10
我知道这不是最好的解决方案,但它确实可以。
Willem 帮助下的替代解决方案。
check :: [Int] -> Bool
check xs = xn == taj xs
where xn = last xs
I would like to check if the first 8 elements's sum/10's remainder is equal to the last (9th) element.
it's a validation algorithm. It works like that. The input list is valid if the first 8 elements's (the sum of odd indexed elements*3 and even indexed elements*7) mod 10 equals to the last element. - comment
您还可以使用 递归 来检查条件,方法是使用累加运行 sum 并在到达最后一个元素时检查它。所以像:
check9 :: [Int] -> Bool
check9 = check9' 8 0
where check9' n s [xn] = n == 0 && s `mod` 10 == xn
check9' n s (x:x2:xs) = check9' (n-2) (s+3*x+7*x2) xs
check9' _ _ _ = False
解决这个问题的更优雅的方法是使用 sum :: Num a => [a] -> a
、zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
、cycle :: [a] -> [a]
和 splitAt :: [a] -> a
:
<b>-- alternative version</b>
check9 :: [Int] -> Bool
check9 xs | (xi,[xn]) <- splitAt 8 xs = xn == mod (sum (zipWith (*) xi $ cycle [3,7])) 10
| otherwise = False