how to do bit shifts and masks in haskell? - haskell

I'm writing a routine to determine whether the high 16 bits of a 32-bit integer have more bits set, or the low bits.
In C, I would write this:
bool more_high_bits(int a) {
if ((a >> 16) == 0) return false; // no high bits
if ((a & 0xFFFF) == 0) return true; // no low bits
// clear one high bit and one low bit, and ask again
return more_high_bits(a&(a - 0x10001));
}
So in Haskell, I'm trying this:
more_high_bits a=if (a `shiftR` 16) /= 0 then 0 else
if ((.&.) a 65535) /= 0 then 1 else
more_high_bits((.&.) a (a-65537))
But it just times out.
What am I doing wrong? What's the more idiomatic way to do this? Please don't code away the shift or the & because I'd like to know how I "should" be using these.
Addendum: I tried this code out on an haskell compiler:
http://www.tutorialspoint.com/compile_haskell_online.php
import Data.Bits
g a=if (a `shiftR` 16) == 0 then 0 else
if ((.&.) a 65535) == 0 then 1 else
g((.&.) a (a-65537))
main = print (g(237))
But it tells me "No instance for (Bits a0) arising from a use of 'g'
The type variable 'a0' is ambiguous"
What is "a0"??

Here's a pretty direct translation of your C code to Haskell:
import Data.Word
import Data.Bits
more_high_bits :: Word32 -> Bool
more_high_bits a
| (a `shiftR` 16) == 0 = False
| (a .&. 0xFFFF) == 0 = True
| otherwise = more_high_bits (a .&. (a - 0x10001))
Your attempt has /= where the C version has ==, which inverts the condition.
a0 is the type variable that the type checker automatically created for your use of g 237. It doesn't know which type you mean because 237 could be any numeric type at all, and g works with all numbers that support bitwise operations and equality. The list of types you could have meant includes (but is not limited to) Int, Integer, Word, ...

Related

fractional type is in Haskell

I want to use rational number type instead of factional type in Haskell (or float/double type in C)
I get below result:
8/(3-8/3)=23.999...
8/(3-8/3)/=24
I know Data.Ratio. However, it support (+) (-) (*) (/) operation on Data.Ratio:
1%3+3%3 == 4 % 3
8/(3-8%3) == 24 % 1
I had checked in Racket:
(= (/ 8 (- 3 (/ 8 3))) 24)
#t
What's correct way to ensure 8/(3-8/3) == 24 in Haskell?
Use an explicit type somewhere in the chain. It will force the entire calculation to be performed with the corrrect type.
import Data.Ratio
main = do
print $ 8/(3-8/3) == 24
print $ 8/(3-8/3) == (24 :: Rational)
Prints
False
True
Data.Ratio.numerator and Data.Ratio.denominator return numerator an denominator of the ratio in reduced form so it is safe to compare denominator to 1 to check if ratio is an integer.
import Data.Ratio
eq :: (Num a, Eq a) => Ratio a -> a -> Bool
eq r i = d == 1 && n == i
where
n = numerator r
d = denominator r
main = print $ (8/(3-8%3)) `eq` 24

Haskell Type errors

First day learning haskell, and coming from a python background I'm really having trouble debugging when it comes to type; Currently I'm working on a simple function to see if a number is a prime;
prime p = if p == 1 then False else if p == 2 then True else if maximum ([if p `mod` x == 0 then x else -1 | x<-[2..(floor(p**0.5))]]) > 0 then False else True
It works when I have a specific number instead of the generic P, but no matter what I try (and I've tried a lot, including just moving onto different problems) I always get some kind of error regarding type. For this current iteration, I'm getting the error
<interactive>:149:1: error:
* Ambiguous type variable `a0' arising from a use of `prime'
prevents the constraint `(RealFrac a0)' from being solved.
Probable fix: use a type annotation to specify what `a0' should be.
These potential instances exist:
instance RealFrac Double -- Defined in `GHC.Float'
instance RealFrac Float -- Defined in `GHC.Float'
...plus one instance involving out-of-scope types
(use -fprint-potential-instances to see them all)
* In the expression: prime 2
In an equation for `it': it = prime 2
<interactive>:149:7: error:
* Ambiguous type variable `a0' arising from the literal `2'
prevents the constraint `(Num a0)' from being solved.
Probable fix: use a type annotation to specify what `a0' should be.
These potential instances exist:
instance Num Integer -- Defined in `GHC.Num'
instance Num Double -- Defined in `GHC.Float'
instance Num Float -- Defined in `GHC.Float'
...plus two others
...plus one instance involving out-of-scope types
(use -fprint-potential-instances to see them all)
* In the first argument of `prime', namely `2'
In the expression: prime 2
In an equation for `it': it = prime 2
If someone could, as well as debugging this particular program, give me a heads up on how to think of haskell types, I'd be incredibly grateful. I've tried looking at learnyouahaskell but so far I've had no luck applying that.
In short: by using mod, floor, and (**) all at the same time, you restrict the type of p a lot, and Haskell fails to find a numerical type to call prime.
The main problem here is in the iterable of your list comprehension:
[2..(floor(p**0.5))]
Here you call p ** 0.5, but since (**) has type (**) :: Floating a => a -> a -> a, that thus means that p has to be an instance of a type that is an instance of the Floating typeclass, for example a Float. I guess you do not want that.
Your floor :: (RealFrac a, Integral b) => a -> b even makes it worse, since now p also has to be of a type that is an instance of the RealFrac typeclass.
On the other hand, you use mod :: Integral a => a -> a -> a, so it means that your p has to be Floating, as well as Integral, which are rather two disjunctive sets: although strictly speaking, we can define such a type, it is rather weird for a number to be both Integral and Floating at the same type. Float is for instance a Floating number, but not Integral, and Int is Integral, but not a Floating type.
We have to find a way to relax the constraints put on p. Since usually non-Integral numbers are no primes at all, we better thus aim to throw out floor and (**). The optimization to iterate up to the square root of p is however a good idea, but we will need to find other means to enforce that.
One way to do this is by using a takeWhile :: (a -> Bool) -> [a] -> [a] where we take elements, until the square of the numbers is greater than p, so we can rewrite the [2..(floor(p**0.5))] to:
takeWhile (\x -> x * x <= p) [2..]
We even can work only with odd elements and 2, by writing it as:
takeWhile (\x -> x * x <= p) (2:[3, 5..])
If we test this with a p that is for instance set to 99, we get:
Prelude> takeWhile (\x -> x * x <= 99) (2:[3, 5..])
[2,3,5,7,9]
If we plug that in, we relaxed the type:
prime p = if p == 1 then False else if p == 2 then True else if maximum ([if p `mod` x == 0 then x else -1 | x <- takeWhile (\x -> x * x <= p) (2:[3, 5..])]) > 0 then False else True
we actually relaxed it enough:
Prelude> :t prime
prime :: Integral a => a -> Bool
and we get:
Prelude> prime 23
True
But the code is very ugly and rather un-Haskell. First of all, you here use maximum as a trick to check if all elements satisfy a predicate. But it makes no sense to do that this way: from the moment one of the elements is dividable, we know that the number is not prime. So we can better use the all :: (a -> Bool) -> [a] -> Bool function. Furthermore conditions are usually checked by using pattern matching and guards, so we can write it like:
prime :: Integral a => a -> Bool
prime n | n < 2 = False
| otherwise = all ((/=) 0 . mod n) divisors
where divisors = takeWhile (\x -> x * x <= n) (2:[3, 5..])
Your code can be simplified as
prime p = if p == 1 then False else
if p == 2 then True else
if maximum ([if p `mod` x == 0 then x else -1 | x<-[2..(floor(p**0.5))]]) > 0
then False else True
=
prime p = if p == 1 then False else
if p == 2 then True else
not (maximum [if p `mod` x == 0 then x else -1 | x<-[2..floor(p**0.5)]] > 0 )
=
prime p = not ( p == 1 ) &&
( p == 2 ||
maximum [if p `mod` x == 0 then x else -1 | x<-[2..floor(p**0.5)]] <= 0 )
=
prime p = p /= 1 &&
( p == 2 ||
maximum [if p `mod` x == 0 then x else -1 | x<-[2..floor(p**0.5)]] == -1 )
=~
prime p = p == 2 || p > 2 && null [x | x <- [2..floor(p**0.5)], p `mod` x == 0]
(convince yourself in the validity of each transformation).
This still gives us a type error of course, because (**) :: Floating a => a -> a -> a and mod :: Integral a => a -> a -> a are conflicting. To counter that, just throw a fromIntegral in there:
isPrime :: Integral a => a -> Bool
isPrime p = p == 2 ||
p > 2 && null [x | x <- [2..floor(fromIntegral p**0.5)], p `mod` x == 0]
and it's working:
~> filter isPrime [1..100]
[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97]

Could not deduce (Num [Char]) arising from the literal

guys, i just started learning haskell (and to code) and i have ran into a problem that i can't figure out. So there is this exercise in which i have to present the number of solutions for a 2nd degree equation.
valid a b c = if [a,b,c] == [0,0,0] then False
else (if [a,b] == [0,0] then False
else (if a == 0 then False
else True)) --function to make sure it is a 2nd degree eq
nRaizes a b c = if valid a b c == False then "not a valid eq"
else (if (b^2 - 4 * a * c) > 0 then 2
else (if ((b^2 - 4 * a * c) == 0) then 1
else 0))
Everything looked fine to me, but when i try to load the script in GHCI i get the error message:
Could not deduce (Num [Char]) arising from the literal ‘2’
from the context (Num a, Ord a)
bound by the inferred type of
nRaizes :: (Num a, Ord a) => a -> a -> a -> [Char]
at ficha1.hs:(18,1)-(21,13)
In the expression: 2
In the expression:
(if (b * b - 4 * a * c) > 0 then
2
else
(if ((b * b - 4 * a * c) == 0) then 1 else 0))
In the expression:
if valid a b c == False then
"not a valid eq"
else
(if (b * b - 4 * a * c) > 0 then
2
else
(if ((b * b - 4 * a * c) == 0) then 1 else 0))
Failed, modules loaded: none.
Can someone explain to me what is wrong with this code? And how can i fix it? Thanks
As I already commented, you should always have a type signature, before even writing any actual code. First make it clear what the purpose of your code is, before actually implementing anything!
So, valid takes three numbers and checks them in some way, yielding False or True – i.e., a boolean. Hence, a valid signature would be
valid :: Int -> Int -> Int -> Bool
This would limit the arguments to machine-sized integers – fast but not overflow-safe. It could also be
valid :: Integer -> Integer -> Integer -> Bool
or, for floating-point real numbers,
valid :: Double -> Double -> Double -> Bool
In fact, you don't need to settle on a particular type: it can be any number type, it just needs to support equality comparison. The “correct” signature would be
valid :: (Num a, Eq a) => a -> a -> a -> Bool
That's indeed also what GHC infers if you just give it the code without a type signature:
Prelude> :t valid
valid :: (Eq a, Num a) => a -> a -> a -> Bool
But the compiler can only get this right by itself because the function valid happens to be type-correct. If you put in some mistake, then the compiler has no idea what the type should be, and hence likely infer some nonsensical type that leads to a cryptic error message. (This is only one of the reasons why you should write the signature first.)
That's what happened in nraized. This also takes three numbers and gives one number. Let's keep it simple:
valid :: Double -> Double -> Double -> Int
That should certainly be ok (though you can certainly make it more generic).
Now the error message is much clearer:
<interactive>:16:87:
Couldn't match expected type ‘Int’ with actual type ‘[Char]’
In the expression: "not a valid eq"
In the expression:
if valid a b c == False then
"not a valid eq"
else
(if (b ^ 2 - 4 * a * c) > 0 then
2
else
(if ((b ^ 2 - 4 * a * c) == 0) then 1 else 0))
What this tells you is that "not a valid eq" is incompatible with the type Int. Pretty obvious actually, isn't it? A function that's supposed to return 0, 1 or 2 shouldn't be able to return a string!
If you really want this to be an error case, you should mark it as such:
nRaizes a b c = if valid a b c == False then error "not a valid eq"
...
Here, the string is not a result: if that case is encountered, the program will simply be aborted and the error message prompted at the user, instead of trying to pass it on to further functions (which couldn't possibly give meaningful results anymore, just yet stranger errors).
A couple of stylistic notes
Generally avoid nesting if with explicit mention of True and False – this is needlessly complicated: comparisons yield booleans anyway. valid just gives false if any of the equalities hold; this could be written
valid a b c = if [a,b,c] == [0,0,0]
|| [a,b] == [0,0]
|| a == 0
then False
else True
...but that's just the same as
valid a b c = not ([a,b,c] == [0,0,0] || [a,b] == [0,0] || a == 0)
or indeed
valid a b c = [a,b,c] /= [0,0,0] && [a,b] /= [0,0] && a /= 0
Anyway, these checks are heavily redundant. If a is not 0 then the list equalities can't possibly hold either! So,
valid a b c = a /= 0
would work just as well. Actually you're not even using the b and c argument, so just write
valid a _ _ = a /= 0
...or just don't define valid by itself at all: simply inline the condition a /= 0.
nRaizes a b c = if (a /= 0) == False then error "not a valid eq"
...
which is of course again completely roundabout: simply use
nRaizes a b c = if a == 0 then error "not a valid eq"
...
That still leaves you with some ugly nested ifs in nasty nested parens. Haskellers don't like that, the preferred style is to use guards:
nRaizes a b c
| a == 0 = error "not a valid eq"
| b^2 - 4*a*c > 0 = 2
| b^2 - 4*a*c == 0 = 1
| otherwise = 0
Still not optimal: you're computing the discriminant twice. Why not:
nRaizes a b c
| a == 0 = error "not a valid eq"
| d > 0 = 2
| d == 0 = 1
| otherwise = 0
where d = b^2 - 4*a*c
While error can be used like that, I wonder why you check this anyway at that point. If a==0 then it's not really a second-order polynomial, but so what? It still has a number of solutions. Really the error case should probably if all the coefficients are zero (because the number of solutions would be infinite). Hence I think the code you really want is probably the following:
nRaizes :: (Eq a, Floating a) => a -> a -> a -> Int
nRaizes a b c
| all (==0) [a,b,c] = error "Equation has infinite solutions"
| d > 0 = 2
| d == 0 = 1
| otherwise = 0
where d = b^2 - 4*a*c

How to temporarily cast integers to larger sizes in Haskell?

I have a problem with number wrapping in the following function:
f :: Word8 -> Word8 -> Word8
f a b = (a + b) `mod` 255
The idea is to add two numbers together, modulus 255 (note 255, not mod 256).
Obviously, the answer to f 252 8 should be 260 mod 255 = 5, but the above function actually returns 4 because 252 + 8 wraps to 4 due to Word8 being able to hold only numbers up to 255. The mod function never is never applied.
I've tried:
f :: Word8 -> Word8 -> Word8
f a b = (fromIntegral a + fromIntegral b) `mod` 255
thinking it will implicitly cast to Integer or Int, but it does not. What is the proper fix so that f doesn't suffer from the wrapping problem and isn't inefficient?
Since you demand that it return a Word8, we can infer that the arguments to mod are both Word8's, hence that the arguments to + are both Word8's, hence that fromIntegral is actually being inferred to have type Word8 -> Word8 -- probably not what you intended!
One fix is to really convert to Integer (or some other type as you prefer) temporarily, then back to Word8:
f a b = fromInteger ((fromIntegral a + fromIntegral b) `mod` 255)
Another solution is to manually check if overflow has happened.
f a b = (sum + if sum < a then 1 else 0) `mod` 255
where sum = a + b
(The final mod operation here really is required, in case sum is 255 and hence no overflow happened!)
If you want, you can delve into low-level Haskell and use primitive operations. I've been pointed in this direction by Michael Snoyman's answer to a related question of mine. Here we don't need to narrow the result because the remainder operation (remWord#) should always deliver a number small enough:
{-# LANGUAGE MagicHash #-}
module Word8Mod where
import GHC.Prim
import GHC.Word
f :: Word8 -> Word8 -> Word8
f (W8# x#) (W8# y#) =
let z# = plusWord# x# y#
in W8# (remWord# z# (int2Word# 255#))

Haskell Int64 inconsistent?

I am trying to solve the problem 2's complement here (sorry, it requires login, but anyone can login with FB/google account). The problem in short is to count the number of ones appearing in the 2's complement representation of all numbers in a given range [A, B] where A and B are within the 32-bit limits (231 in absolute value). I know my algorithm is correct (it's logarithmic in the bigger absolute value, since I already solved the problem in another language).
I am testing the code below on my machine and it's giving perfectly correct results. When it runs on the Amazon server, it gives a few wrong answers (obviously overflows) and also some stack overflows. This is not a bug in the logic here, because I test the same code on my machine on the same test inputs and get different results. For example, for the range [-1548535525, 662630637] I get 35782216444 on my machine, while according to the tests, my result is some negative overflow value.
The only problem I can think of, is that perhaps I am not using Int64 correctly, or I have a wrong assumption about it's operation.
Any help is appreciated. Code is here.
The stack overflows are a bug in the logic.
countOnes !a !b | a == b = countOnes' a
countOnes' :: Int64 -> Integer
countOnes' !0 = 0
countOnes' !a = (fromIntegral (a .&. 1)) + (countOnes' (a `shiftR` 1))
Whenever you call countOnes' with a negative argument, you get a nonterminating computation, since the shiftR is an arithmetic shift and not a logical one, so you always shift in a 1-bit and never reach 0.
But even with a logical shift, for negative arguments, you'd get a result 32 too large, since the top 32 bits are all 1.
Solution: mask out the uninteresting bits before calling countOnes',
countOnes !a !b | a == b = countOnes' (a .&. 0xFFFFFFFF)
There are some superfluous guards in countOnes,
countOnes :: Int64 -> Int64 -> Integer
countOnes !a !b | a > b = 0
-- From here on we know a <= b
countOnes !a !b | a == b = countOnes' (a .&. 0xFFFFFFFF)
-- From here on, we know a < b
countOnes !0 !n = range + leading + (countOnes 0 (n - (1 `shiftL` m)))
where
range = fromIntegral $ m * (1 `shiftL` (m - 1))
leading = fromIntegral $ (n - (1 `shiftL` m) + 1)
m = (getLog n) - 1
-- From here on, we know a /= 0
countOnes !a !b | a > 0 = (countOnes 0 b) - (countOnes 0 (a - 1))
-- From here on, we know a < 0,
-- the guard in the next and the last equation are superfluous
countOnes !a !0 | a < 0 = countOnes (maxInt + a + 1) maxInt
countOnes !a !b | b < 0 = (countOnes a 0) - (countOnes (b + 1) 0)
countOnes !a !b | a < 0 = (countOnes a 0) + (countOnes 0 b)
The integer overflows on the server are caused by
getLog :: Int64 -> Int
--
countOnes !0 !n = range + leading + (countOnes 0 (n - (1 `shiftL` m)))
where
range = fromIntegral $ m * (1 `shiftL` (m - 1))
leading = fromIntegral $ (n - (1 `shiftL` m) + 1)
m = (getLog n) - 1
because the server has a 32-bit GHC, while you have a 64-bit one. The shift distance/bit width m is an Int (and because it's used as the shift distance, it has to be).
Therefore
m * (1 `shiftL` (m-1))
is an Int too. For m >= 28, that overflows a 32-bit Int.
Solution: remove a $
range = fromIntegral m * (1 `shiftL` (m - 1))
Then the 1 that is shifted is an Integer, hence no overflow.

Resources