How to pass a list received in one function to another function - in Haskell?
I'm writing a function that checks if the mod of a (transformed) list is equal to zero or not, I'm using two functions, but I don't know how I can pass the list received in the "valida" function to the "duplicador" function.
To work, I'm passing the list inside the "valida" function, but not as a parameter.
I wish that where the duplicador [1, 3, 8, 6]
I could pass the argument/list received in the "valida" function
module Main where
duplicador :: [Integer] -> [Integer]
duplicador [] = []
duplicador (x:[]) = [x]
duplicador (x:y:zs)
| (length (x:y:zs)) `mod` 2 /= 0 = x : y*2 : duplicador zs
| otherwise = x*2 : y : duplicador zs
valida :: [Integer] -> Bool
valida r
| r == 0 = True
| otherwise = False
where
r = foldr (\x y -> x y) 0 (duplicador [1, 3, 8, 6]) `mod` 10
main = do
print(valida [1, 3, 8, 6])```
CodePudding user response:
You are shadowing the argument r in valida. Renaming r to something let's you use it.
valida :: [Integer] -> Bool
valida entrada
| r == 0 = True
| otherwise = False
where
r = foldr (\x y -> x y) 0 (duplicador entrada) `mod` 10
We can also improve the code a bit further. foldr (\x y -> x y) 0
can be simplified to foldr ( ) 0
, but still it is a very common pattern, we can replace it with sum
. And for the pattern if bool then true else false
is simply bool
, rendering:
valida r = sum (duplicador r) `mod` 10 == 0