Order-dependant Bit Fields - language-agnostic

How would one go about storing positional information in bit fields (the order in which the fields are OR'd or otherwise)?
Background: It popped into my head last night while writing a part of my game engine. Let's say that we are trying to describe a colour, and as part of that we have the colours that are present in the descriptor (and their order). For example we have the following colour orders on most graphics cards today:
RGBA
BGRA
The following flags can be used to describe colours that are supported:
None = 0x0
A = 0x1
R = 0x2
G = 0x4
B = 0x8
However, by using those fields A | R | G | B is the same thing as B | G | R | A. How would you design the flags and/or operations that can be used to add positional dependence? Bonus marks for adding exclusivity (you can't have R and G in position 1, for example) and for utility (some clever way that it could be used, possibly in this case scenario).

You can shift the bit field before adding each flag, by the number of bits required for each unique flag. The following flags would be used:
None = 0x0
A = 0x1
R = 0x2
G = 0x4
B = 0x8
Shift = 0x4
Mask = 0xF (A | R | G | B)
On a little-endian system you would shift it left by Shift (<<) before each OR. The shift left on None can be eliminated because 0 << x = 0. Given the original example:
A1 = A
A1R2 = (A1 << Shift) | R
A1R2G3 = (A1R1 << Shift) | G
A1R2G3B4 = (A1R1G3 << Shift) | B
B1 = B
B1G2 = (B1 << Shift) | G
B1G2R3 = (B1G2 << Shift) | R
B1G2R3A4 = (B1G2R3 << Shift) | A
To extract the position of each you would repeatedly shift it right (little-endian) and AND it with Mask. Repeating this until the current value reaches None would give you the reverse order.
let cur = the bit field we want to check
loop until cur = None:
let val = cur AND Mask
emit the name of val
let cur = cur >> Shift
This does not offer exclusivity (you can easily do a AAGB) and it doesn't look like it has any utility.

Related

What is = followed by == operation?

I've encountered this code and don't know what its performing :
yk = y == k;
Recreating :
>> a = 1
a = 1
>> b = 2
b = 2
>> c = 3
c = 3
>> a = b == c
a = 0
>>
I think it is a boolean operation. If y == k then yk = 1 else yk = 0 ?
In order to figure out what your statement means, you can refer to Octave's operator precedence. As you can see from that list, assignment (=) has the lowest precedence of any operator (including ==). As a result, the line that you have posted translates to
Perform the relational operation y == k
Assign the result to the variable yk

MIPS Programming instruction count issue

I wrote this mips code to find the gcf but I am confused on getting the number of instructions executed for this code. I need to find a linear function as a function of number of times the remainder must be calculated before an answer. i tried running this code using Single step with Qtspim but not sure on how to proceed.
gcf:
addiu $sp,$sp,-4 # adjust the stack for an item
sw $ra,0($sp) # save return address
rem $t4,$a0,$a1 # r = a % b
beq $t4,$zero,L1 # if(r==0) go to L1
add $a0,$zero,$a1 # a = b
add $a1,$zero,$t4 # b = r
jr gcf
L1:
add $v0,$zero,$a1 # return b
addiu $sp,$sp,4 # pop 2 items
jr $ra # return to caller
There is absolutely nothing new to show here, the algorithm you just implemented is the Euclidean algorithm and it is well known in the literature1.
I will nonetheless write an informal analysis here as link only questions are evil.
First lets rewrite the code in an high level formulation:
unsigned int gcd(unsigned int a, unsigned int b)
{
if (a % b == 0)
return b;
return gcd(b, a % b);
}
The choice of unsigned int vs int was dicated by the MIPS ISA that makes rem undefined for negative operands.
Out goal is to find a function T(a, b) that gives the number of step the algorithm requires to compute the GDC of a and b.
Since a direct approach leads to nothing, we try by inverting the problem.
What pairs (a, b) makes T(a, b) = 1, in other words what pairs make gcd(a, b) terminates in one step?
We clearly must have that a % b = 0, which means that a must be a multiple of b.
There are actually an (countable) infinite number of pairs, we can limit our selves to pairs with the smallest, a and b2.
To recap, to have T(a, b) = 1 we need a = nb and we pick the pair (a, b) = (1, 1).
Now, given a pair (c, d) that requires N steps, how do we find a new pair (a, b) such that T(a, b) = T(c, d) + 1?
Since gcd(a, b) must take one step further then gcd(c, d) and since starting from gcd(a, b) the next step is gcd(b, a % b) we must have:
c = b => b = c
d = a % b => d = a % c => a = c + d
The step d = a % c => a = c + d comes from the minimality of a, we need the smallest a that when divided by c gives d, so we can take a = c + d since (c + d) % c = c % c d % c = 0 + d = d.
For d % c = d to be true we need that d < c.
Our base pair was (1, 1) which doesn't satisfy this hypothesis, luckily we can take (2, 1) as the base pair (convince your self that T(2, 1) = 1).
Then we have:
gcd(3, 2) = gcd(2, 1) = 1
T(3, 2) = 1 + T(2, 1) = 1 + 1 = 2
gcd(5, 3) = gcd(3, 2) = 1
T(5, 3) = 1 + T(3, 2) = 1 + 2 = 3
gcd(8, 5) = gcd(5, 3) = 1
T(8, 5) = 1 + T(5, 3) = 1 + 3 = 4
...
If we look at the pair (2, 1), (3, 2), (5, 3), (8, 5), ... we see that the n-th pair (starting from 1) is made by the number (Fn+1, Fn).
Where Fn is the n-th Fibonacci number.
We than have:
T(Fn+1, Fn) = n
Regarding Fibonacci number we know that Fn ∝ φn.
We are now going to use all the trickery of asymptotic analysis, particularly in the limit of the big-O notation considering φn or φn + 1 is the same.
Also we won't use the big-O symbol explicitly, we rather assume that each equality is true in the limit. This is an abuse, but makes the analysis more compact.
We can assume without loss of generality that N is an upper bound for both number in the pair and that it is proportional to φn.
We have N ∝ φn that gives logφ N = n, this ca be rewritten as log(N)/log(φ) = n (where logs are in base 10 and log(φ) can be taken to be 1/5).
Thus we finally have 5logN = n or written in reverse order
n = 5 logN
Where n is the number of step taken by gcd(a, b) where 0 < b < a < N.
We can further show that if a = ng and b = mg with n, m coprimes, than T(a, b) = T(n, m) thus the restriction of taking the minimal pairs is not bounding.
1 In the eventuality that you rediscovered such algorithm, I strongly advice against continue with reading this answer. You surely have a sharp mind that would benefit the most from a challenge than from an answer.
2 We'll later see that this won't give rise to a loss of generality.

Call comparison operators in Haskell

i need to find out if the difference from differenceAB is the smallest:
smallestDifference3 :: Int -> Int -> Int -> Int
smallestDifference a b c
| differenceAB < differenceBC < differenceAC = differenceAB
| otherwise = differenceAB
where differenceAB
| a < b = -(a - b)
| otherwise = a - b
differenceBC
| b < c = -(b - c)
| otherwise = b - c
differenceAC
| a < c = -(a - c)
| otherwise = a - c
but i get this error:
cannot mix `<' [infix 4] and `<' [infix 4] in the same infix expression
how to solve my problem? anybody know´s? greetingS!
There are a couple of problems here.
You have 3 exactly identical functions. Probably you want values:
smallestDifference a b c = ....
where
diffAC = abs(a-c)
diffAB = abs(a-b)
diffBC = abs(b-c)
Now for the expression, you can't write
diffAC < diffAB < diffBC
since (<) is a non-associative operator. Which means you must write explicit parentheses:
(diffAC < diffAB) < diffBC
But this doesnt type check, because for the second (<) the left hand side is Bool, but the right hand side is Int. What you want is
(diffAC < diffAB) && (diffAB < diffBC)
i.e. if ac is lower then ab and ab is lower than bc
If you just want to find the smallest difference, following will work.
smallestdiff a b c = minimum [abs $ a-b, abs $ b-c, abs $a-c]
There is no such thing as chaining operators in Haskell. You should use explicit logical operations:
smallestDifference3 :: Int -> Int -> Int -> Int
smallestDifference a b c
| (differenceAB < differenceBC) && (differenceBC < differenceAC) = differenceAB
| otherwise = differenceAB
BTW, your code is weird, you return differenceAB from both guard clauses. It is not clear what you want to achieve, so I cannot help further.

Compute next prime number in Haskell

I am trying to compute the next closest prime number after a number is entered with Haskell,
I have coded 2 functions isPrime and nextPrime
Here is my code:
isPrime :: Int -> Bool
isPrime x | x < 2 = False
| otherwise = prime (2:[3,4..(x-1)])
where
prime (y:z)
| x < y ^ 2 = True
| x `mod` y == 0 = False
| otherwise = prime z
nextPrime :: Int -> Int
nextPrime n | isPrime n == True = n
| otherwise = nextPrime n
where
n = n + 1
The problem I have is that I get this error when I run it : * Exception: "<<"loop">>"
I don't know what's wrong, is it an infinite loop?
You cannot change the value of variables in Haskell. This means that you cannot execute
n = n + 1
since that would change the value of n. In Haskell, n is a name that always refers to the same value inside the function it is used. If n starts out as 3, n will always be 3. You could do,
next = n + 1
and then also change
| otherwise = nextPrime n
into
| otherwise = nextPrime next
This will not change the value of any variable, but instead create a new variable with the new value – something you often do in Haskell!
Just change the definition of nextPrime to
nextPrime :: Int -> Int
nextPrime n | isPrime n = n -- don't need to compare to True here
| otherwise = nextPrime (n+1)
You generate an infinite regress when you try to define n = n + 1, as the runtime would attempt to expand this as
n = n + 1
= (n + 1) + 1
= ((n + 1) + 1) + 1
= ...
Fortunately, the compiler is able to detect this kind of infinite regress and warn you about it!

How do I create Haskell functions that return functions?

I would like to create three Haskell functions: a, b, and c.
Each function is to have one argument. The argument is one of the three functions.
I would like function a to have this behavior:
if the argument is function a then return function a.
if the argument is function b then return function b.
if the argument is function c then return function a.
Here's a recap of the behavior I desire for function a:
a a = a
a b = c
a c = a
And here's the behavior I desire for the other two functions:
b a = a
b b = a
b c = c
c a = c
c b = b
c c = c
Once created, I would like to be able to compose the functions in various ways, for example:
a (c b)
= a (b)
= c
How do I create these functions?
Since you have given no criteria for how you are going to observe the results, then a = b = c = id satisfies your criteria. But of course that is not what you want. But the idea is important: it doesn't just matter what behavior you want your functions to have, but how you are going to observe that behavior.
There is a most general model if you allow some freedom in the notation, and you get this by using an algebraic data type:
data F = A | B | C
deriving (Eq, Show) -- ability to compare for equality and print
infixl 1 %
(%) :: F -> F -> F
A % A = A
A % B = C
A % C = A
B % A = A
...
and so on. Instead of saying a b, you have to say A % B, but that is the only difference. You can compose them:
A % (C % B)
= A % B
= B
and you can turn them into functions by partially applying (%):
a :: F -> F
a = (A %)
But you cannot compare this a, as ehird says. This model is equivalent to the one you specified, it just looks a little different.
This is impossible; you can't compare functions to each other, so there's no way to check if your argument is a, b, c or something else.
Indeed, it would be impossible for Haskell to let you check whether two functions are the same: since Haskell is referentially transparent, substituting two different implementations of the same function should have no effect. That is, as long as you give the same input for every output, the exact implementation of a function shouldn't matter, and although proving that \x -> x+x and \x -> x*2 are the same function is easy, it's undecidable in general.
Additionally, there's no possible type that a could have if it's to take itself as an argument (sure, id id types, but id can take anything as its first argument — which means it can't examine it in the way you want to).
If you're trying to achieve something with this (rather than just playing with it out of curiosity — which is fine, of course), then you'll have to do it some other way. It's difficult to say exactly what way that would be without concrete details.
Well, you can do it like this:
{-# LANGUAGE MagicHash #-}
import GHC.Prim
import Unsafe.Coerce
This function is from ehird's answer here:
equal :: a -> a -> Bool
equal x y = x `seq` y `seq`
case reallyUnsafePtrEquality# x y of
1# -> True
_ -> False
Now, let's get to business. Notice that you need to coerce the arguments and the return values as there is no possible type these functions can really have, as ehird pointed out.
a,b,c :: x -> y
a x | unsafeCoerce x `equal` a = unsafeCoerce a
| unsafeCoerce x `equal` b = unsafeCoerce c
| unsafeCoerce x `equal` c = unsafeCoerce a
b x | unsafeCoerce x `equal` a = unsafeCoerce a
| unsafeCoerce x `equal` b = unsafeCoerce a
| unsafeCoerce x `equal` c = unsafeCoerce c
c x | unsafeCoerce x `equal` a = unsafeCoerce c
| unsafeCoerce x `equal` b = unsafeCoerce b
| unsafeCoerce x `equal` c = unsafeCoerce c
Finally, some tests:
test = a (c b) `equal` c -- Evaluates to True
test' = a (c b) `equal` a -- Evaluates to False
Ehh...
As noted, functions can't be compared for equality. If you simply want functions that satisfy the algebraic laws in your specificiation, making them all equal to the identity function will do nicely.
I hope you are aware that if you post a homework-related question to Stack Overflow, the community expects you to identify it as such.