Home > Net >  Function that adds numbers of the list are divisible by 3,4 but not by 6
Function that adds numbers of the list are divisible by 3,4 but not by 6

Time:12-12

Write a function sumdv that holds a list of integers and adds up all numbers in the list that are divisible by 3 or 4 but not by 6. The functions sum, filter, convolutions and list generators are forbidden.

sumdv :: [Integer] -> [a] -> [Integer]
sumdv = add
sumdv [] = 0
sumdv (x:xs) 
    | mod 3 x == 0 || mod 4 x == 0 = x   sumdv (x:xs)
    | mod 6 x == 0 = sumdv (x:xs) 

Hey guys again, I´m a little bit confused about the right type, because the system shows only "Variable not in scope: sumdv :: [Integer] -> t". My thoughs are that at first I have a list with Integer, because of the fact that it must be "whole numbers" then the gave me a list of different elements that must be add together for me it is: [Integer] -> [a] -> a but it didnt work :( –

CodePudding user response:

I would say that there are multiple mistakes:

  • type is wrong (based on the description you should accept collection of elements and return one)
  • seems like sumdv = add should be just removed
  • sumdv (x:xs) calls lead to infinite recursion (you are calling function passing the same input without modification)
  • mod arguments are in the wrong order
  • mod x 6 == 0 pattern guard should be before mod x 3 == 0 || mod x 4 == 0 cause only first matching guard is evaluated, and you will not filter out number divisible by 6 if mod x 3 == 0 is placed first
  • you are missing pattern guard for otherwise case (when number is not divisible by 3,4 or 6)

Taking in account all the notes above sample implementation can look like this:

sumdv [] = 0
sumdv (x:xs)
    | mod x 6 == 0                  = sumdv (xs) 
    | mod x 3 == 0 || mod x 4 == 0  = x   sumdv (xs)
    | otherwise                     = sumdv (xs) 
  • Related