# How can I check if integers from one list are divisible integers from another?

I am trying to create a function that takes `Int`

( `n`

) and a list `k`

of `Int`

s and returns the sum of all numbers `1 <= i <= n`

that are divisible by at least one of the integers from the list `k`

.

``````addl::Int -> [Int] -> Int
addl x (y:ys) = if  ((map [1..x] `mod` y) == 0)
then y + addl x ys
else 0 + addl x ys
```

```

This is what I got, but I get this message:

``````Couldn't match expected type `a0 -> b0' with actual type `[t0]'
In the first argument of `map', namely `[1 .. x]'
In the first argument of `mod', namely `map [1 .. x]'
In the first argument of `(==)', namely `(map [1 .. x] `mod` y)'
```

```

which I tried to figure out but didn't figure it out yet. All help is greatly appreciated.

+3

source to share

`map`

expects the function to be the first argument, but you supply a list to it.

The error message says the same. This means that the expression is `((map [1..x] `mod` y) == 0)`

parsed as

``````(==)   -- In the first argument of `(==)', namely `(map [1 .. x] `mod` y)'
mod     -- In the first argument of `mod', namely `map [1 .. x]'
map [1..x]  -- In the first argument of `map', namely `[1 .. x]'
y
0
-- Couldn't match expected type `a0 -> b0' with actual type `[t0]'
```

```

`map`

A type

``````Prelude> :t map
map :: (a -> b) -> [a] -> [b]

Prelude> :t [undefined]
[undefined] :: [a]
```

```

and `(a1 -> b1)`

and `[a2]`

do not match.

Instead of mixing up the two actions (filtering and summing) in your code, vaguely (you even summarize the wrong variable `y`

there), it's easier to simplify the process for the first lookup, and only then, summing:

``````addl::Int -> [Int] -> Int
addl n ks = sum                                         -- then, sum
[i | i <- [1..n], isDividedByAny i ks]   -- first, search
where
isDividedByAny i ks =
any
[ rem i k == 0 | k <- ks]
```

```

Here we are using a built-in `any`

type function `(a -> Bool) -> [a] -> Bool`

(i.e. it takes a predicate function, a list of values ​​and returns a boolean value).

Notice how I am calling your `k`

list `ks`

here to suggest the "k" list to him. This is idiomatic in Haskell.

+3

source

All Articles