I have tried to implement a guard safe version this in the past, to no
avail. The limitation that I can remember was to not to be able to use
a conditional in the guards, which let me to create conditionals using
boolean operators.. it didn't work.
I will be happy to see a solution.

 On Mon, 8 Aug 2016 03:25:34 -0700 (PDT)
Wiebe-Marten Wijnja <[email protected]> wrote:

> I have been fiddling around with this for quite some time. Other than
> I thought, `div` also uses truncated division. (It makes sense, as it 
> complements `rem`). This makes above implementation moot.
> 
> To be able to create `mod`, we need a floored division. I have not
> yet found a way to do this without using conditionals (an easy way
> would be to subtract one from the result of `div` iff the result is a
> negative number), which are not allowed in guard clauses.
> 
> I will not give up yet, but it might very well be impossible.
> 
> On Monday, August 8, 2016 at 10:24:12 AM UTC+2, Wiebe-Marten Wijnja
> wrote:
> >
> > Elixir has `rem(dividend, divisor)` to calculate the remainder of
> > an integer division. However, as you probably know, there are
> > different ways to handle remainders with negative numbers:
> >
> > `rem` will take the remainder, but use the sign of the dividend,
> > which means that the following function definition:
> >
> > def is_odd(n)
> >   rem(n, 2) == 1
> > end
> >
> > will fail for -1, -3, etc, as `rem(-3, 2)`, for instance, has as
> > answer *-1*.
> >
> > It is also possible to make a *modulo* function, which uses the
> > sign of the divisor. This has the advantage over the remainder
> > function that it maps the whole domain of integers unto a smaller,
> > cyclic, range of numbers. This is highly useful in many algorithms
> > dealing with numbers or indices.
> >
> > Many programming languages both have a remainder and a modulo
> > function. I have seen multiple people roll their own definitions of
> > `mod` in their Elixir libraries, because they needed it. 
> >
> > I propose the addition of the modulo function, `mod(a, n)` to
> > Elixir.
> >
> > A possible implementation is as follows:
> >
> > defmacro mod(a, n) do
> >   quote do
> >     unquote(a) - (unquote(n) * div(unquote(a), unquote(n))
> >   end
> > end
> >
> > This implementation is guard-safe, so it can be used anywhere where
> > `div` and `rem` are also allowed.
> >
> >  
> 

-- 
You received this message because you are subscribed to the Google Groups 
"elixir-lang-core" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/elixir-lang-core/20160808212901.1360e245.eksperimental%40autistici.org.
For more options, visit https://groups.google.com/d/optout.

Reply via email to