Iterate over a list and apply modulus/remainder to each element

Viewed 192

A method that returns a new list formed by applying the second argument as a modulus operand on each list member, with two arguments: a list and a numerical value.

My current method only applies modulus operand to the first element and not all the elements.

I'm trying to use the cons operator to build the new list.

modList([Head | Tail], Num) -> [Head rem Num | Tail].
2 Answers

You're on the right track. You're writing a recursive function, so what you need next are two things:

  1. The recursive step: At some point in the body of your function, you need to apply your same function to the rest of the list (i.e. modList(Tail)).
  2. The base case: If you apply the recursive step repeatedly, since you're removing one element from the list on each iteration, at some point, you'll have a list that doesn't match your function head pattern ([Head | Tail]). That will lead to a function_clause error that you can fix by… of course… adding a clause for that list. Since that clause will likely not need to be recursive (i.e. it will return a hardcoded value), that will close the recursion loop and your recursive function will be complete.

Extra tip: It's generally more idiomatic to use snake_case instead of camelCase for function names, module names, and atoms in general in Erlang. In other words, a more common name for your function would be mod_list/2.

You can do something like

> Num = 5.
5
> [X rem Y || X <- [1, 2, 3, 4, 5, 6, 7], Y <- [Num]].
[1,2,3,4,0,1,2]
Related