operator precedence in Haskell - haskell

I am confused about the rules for operator precedence in Haskell.
More specifically, why is this:
*Main> 2 * 3 `mod` 2
0
different than this?
*Main> 2 * mod 3 2
2

Function calls bind the tightest, and so
2 * mod 3 2
is the same as
2 * (mod 3 2)
Keep in mind that mod is not being used as an operator here since there are no backticks.
Now, when mod is used in infix form it has a precedence of 7, which (*) also has. Since they have the same precendence, and are left-associative, they are simply parsed from left to right:
(2 * 3) `mod` 2

2*3 = 6 and then mod 2 = 3 with no remainder ... so 6 mod 2 = 0 is your answer there.
In your second case you are doing 2 * the result of mod 3 2 which is 2 * 1 = 2. Therefore your answer is 2.... Your operator precedence remains the same, you just arranged it so the answers were expressed accordingly.

Related

Last digit of a huge number

I'm solving Last digit of a huge number in Codewars.
I managed to find out a way to calculate odd number ^ odd number and odd number ^ even number. However I got stuck in even ^ even/odd as the relation between the number and its power's mod is not obvious.
Here's what I managed to get:
lastDigit :: [Integer] -> Integer
lastDigit = (`rem` 10) . go
where
go [] = 1
go [x] = x
go (x : y : r)
| odd x && odd y = x ^ (go (y : r) `rem` (x + 1))
| odd x && even y = x ^ (foldMod y (go r) (x + 1))
| otherwise = -- any hint?
foldMod :: Integer -> Integer -> Integer -> Integer
foldMod _ 0 _ = 1
foldMod base 1 modulo = base `rem` modulo
foldMod base power modulo = (base * foldMod base (power -1) modulo) `rem` modulo
Can anyone give some hints on how to do about the even cases?
I recommend rethinking your approach, and beginning with a more general function. Specifically, can you compute
powMod :: Integer -> [Integer] -> Integer
where powMod base exponents computes the exponential tower described in the problem mod base? Note that when you recurse, you will recurse with a different base -- because the cycle lengths of the various first exponents are not necessarily all divisors of base. For example, in base 10, any first exponent with a last digit of 7 cycles every four goes, not every ten; the last digit of the powers goes like this:
x 0 1 2 3 4 5 6 7
7^x `mod` 10 1 7 9 3 1 7 9 3
You'll also want to watch out for situations where the first exponent is not itself in the eventual cycle that gets reached; for example, in base 4, we have:
x 0 1 2 3 4 5 6 7
2^x `mod` 4 1 2 0 0 0 0 0 0
So you can't look at just x `mod` 1 and infer from it what 2^x `mod` 4 is, even though the cycle length is 1. (There are other examples, like 2^x `mod` 12, where the cycle is longer than 1 and still doesn't have the original 2 in it.)
You do not need to calculate the entire number to know the last digit, there are fast, and less fast approaches that can calculate the last digit without having to worry about all the other digits.
A simple approach that can calculate ab in O(log b) time is by making use of the following equivalence:
(a×b) mod m = ((a mod m) × (b mod m)) mod m.
This means we can each time calculate the last digit and work with that. It thus means that as long as we can represent all numbers up to 81, we can calculate the ab mod m powMod m a b:
powMod :: Int -> Int -> Int -> Int
powMod m = go
where go _ 0 = 1
go a b | even n = r
| otherwise = (x * r) `mod` m
where r = go ((a*a) `mod` m) (div b 2) `mod` m
If we assume we can calculate modulo, divide by two, check if a value is even, etc. in constant time, this runs in O(log b).
But we can even do this faster by looking for cycles. Imagine that we have to calculate a power of 7, then 7^0 is 1, 7^1 is 7, 7^2 mod 10 = 9, etc. We can make a table with multiplications:
× │ 0 1 2 3 4 5 6 7 8 9
──┼─────────────────────
0 │ 0 0 0 0 0 0 0 0 0 0
1 │ 1 2 3 4 5 6 7 8 9
2 │ 4 6 8 0 2 4 8 6
3 │ 9 2 5 8 1 4 7
4 │ 6 0 4 8 2 6
5 │ 5 0 5 0 5
6 │ 6 2 8 4
7 │ 9 6 3
8 | 4 2
9 | 1
If we thus look at the last digit for a power of 7, we see that for:
power │ │ last digit
──────────────────────────
0 │ │ 1
1 │ 7*1 │ 7
2 │ 7*7 │ 9
3 │ 7*9 │ 3
4 │ 7*3 │ 1
This thus means that there is a cycle, indeed, after each multiplication with 7, we move to the next state, and thus obtain the following graph:
1 → 7 → 9 → 3
↖_______________/
This thus means that the cycle has a length of four. It thus means that if we have to calculate 7 to the power of for example 374, then we know that these are 93 cycles of length four that have thus no impact, and two extra moves, we thus know that the last digit of 7393 is 9, without having to compute this number. Since such cycles has a maximum length of 10, this can thus done in constant time do determine the last digit of the decimal number.

Floor division and modulo with negative number [duplicate]

This question already has answers here:
Floor division with negative number
(4 answers)
Closed 2 years ago.
print(-2//4)
The output is -1. I do not understand the logic. Why the negative modulo?
(-2) ÷ 4 gives -1 remainder 2.
The relation that has to be correct is that for integers a and b
a = (a//b) * b + (a%b)
In this case, b is 4, and the remainder a%b must be between 0 (inclusive) and 4 (exclusive). So the only values for a//b and a%b that work are
a//b = -1
a%b = 2
which gives
-2 = -1 * 4 + 2
a a//b b a%b
TLDR
The precise value of (-2) / 4 is -0.5. The greatest integer not greater than -0.5 is -1.

How to remove an element from a list in J by index?

The rather verbose fork I came up with is
({. , (>:#[ }. ]))
E.g.,
3 ({. , (>:#[ }. ])) 0 1 2 3 4 5
0 1 2 4 5
Works great, but is there a more idiomatic way? What is the usual way to do this in J?
Yes, the J-way is to use a 3-level boxing:
(<<<5) { i.10
0 1 2 3 4 6 7 8 9
(<<<1 3) { i.10
0 2 4 5 6 7 8 9
It's a small note in the dictionary for {:
Note that the result in the very last dyadic example, that is, (<<<_1){m , is all except the last item.
and a bit more in Learning J: Chapter 6 - Indexing: 6.2.5 Excluding Things.
Another approach is to use the monadic and dyadic forms of # (Tally and Copy). This idiom of using Copy to remove an item is something that I use frequently.
The hook (i. i.##) uses Tally (monadic #) and monadic and dyadic i. (Integers and Index of) to generate the filter string:
2 (i. i.##) 'abcde'
1 1 0 1 1
which Copy (dyadic #) uses to omit the appropriate item.
2 ((i. i.##) # ]) 0 1 2 3 4 5
0 1 3 4 5
2 ((i. i.##) # ]) 'abcde'
abde

J: Applying two arguments to a monadic verb produces strange results

I was wondering what would happen if I apply two arguments to this verb: 3&*.
If the left one is 1 all works as if it was only one argument:
1 (3&*) 3
9
1 (3&*) 4
12
1 (3&*) 5
15
If I change it I discover why that worked:
2 (3&*) 5
45
3 (3&*) 5
135
10 (3&*) 5
295245
It seems that the left argument is interpreted as a repetition like ^:. So the last one is equal to 3 * 3 * 3 * 3 * 3 * 3 * 3 * 3 * 3 * 3 * 5 (10 3's), or:
5 * 3^10
295245
Can you explain this weird behavior? I was expecting something like domain error (which is ubiquitous), and that is thrown if I try to use fndisplay:
require 'j/addons/general/misc/fndisplay.ijs'
defverbs 'f'
defnouns 'x y n'
x (n&*) y
|domain error
| x (n&*)y
it is documented.
x m&v y ↔ m&v^:x y
x u&n y ↔ u&n^:x y
&Bond from J dictionary

How can I implement a grouping algorithm in J?

I'm trying to implement A006751 in J. It's pretty easy to do in Haskell, something like:
concat . map (\g -> concat [show $ length g, [g !! 0]]) . group . show
(Obviously that's not complete, but it's the basic heart of it. I spent about 10 seconds on that, so treat it accordingly.) I can implement any of this fairly easily in J, but the part that eludes me is a good, idiomatic J algorithm that corresponds to Haskell's group function. I can write a clumsy one, but it doesn't feel like good J.
Can anyone implement Haskell's group in good J?
Groups are usually done with the /. adverb.
1 1 2 1 </. 'abcd'
┌───┬─┐
│abd│c│
└───┴─┘
As you can see, it's not sequential. Just make your key sequential like so (essentially determining if an item is different from the next, and do a running sum of the resulting 0's and 1's):
neq =. 13 : '0, (}. y) ~: (}: y)'
seqkey =. 13 : '+/\neq y'
(seqkey 1 1 2 1) </. 'abcd'
┌──┬─┬─┐
│ab│c│d│
└──┴─┴─┘
What I need then is a function which counts the items (#), and tells me what they are ({. to just pick the first). I got some inspiration from nubcount:
diffseqcount =. 13 : ',(seqkey y) (#,{.)/. y'
diffseqcount 2
1 2
diffseqcount 1 2
1 1 1 2
diffseqcount 1 1 1 2
3 1 1 2
If you want the nth result, just use power:
diffseqcount(^:10) 2 NB. 10th result
1 3 2 1 1 3 2 1 3 2 2 1 1 3 3 1 1 2 1 3 2 1 2 3 2 2 2 1 1 2
I agree that /. ( Key ) is the best general method for applying verbs to groups in J. An alternative in this case, where we need to group consecutive numbers that are the same, is dyadic ;. (Cut):
1 1 0 0 1 0 1 <(;.1) 3 1 1 1 2 2 3
┌─┬─────┬───┬─┐
│3│1 1 1│2 2│3│
└─┴─────┴───┴─┘
We can form the frets to use as the left argument as follows:
1 , 2 ~:/\ 3 1 1 1 2 2 3 NB. inserts ~: in the running sets of 2 numbers
1 1 0 0 1 0 1
Putting the two together:
(] <;.1~ 1 , 2 ~:/\ ]) 3 1 1 1 2 2 3
┌─┬─────┬───┬─┐
│3│1 1 1│2 2│3│
└─┴─────┴───┴─┘
Using the same mechanism as suggested previously:
,#(] (# , {.);.1~ 1 , 2 ~:/\ ]) 3 1 1 1 2 2 3
1 3 3 1 2 2 1 3
If you are looking for a nice J implementation of the look-and-say sequence then I'd suggest the one on Rosetta Code:
las=: ,#((# , {.);.1~ 1 , 2 ~:/\ ])&.(10x&#.inv)#]^:(1+i.#[)
5 las 1 NB. left arg is sequence length, right arg is starting number
11 21 1211 111221 312211

Resources