Call comparison operators in Haskell - function

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.

Related

Haskell Integer Odd Digits Checker

I seem to be stuck on a question and have no idea how to approach it or what Im doing wrong with my current code.
I have to write a function called oddDigits which takes a single integer argument and returns a boolean result. It should return True if and only if the argument is a positive integer with an odd number of digits. If the argument is zero or negative, the function should stop with an error message.
Also, cant convert the argument into a string. Have to use recursion.
I have a feeling each digit could be stored in a list recursively and then the length of the list could determine the answer.
So far, I have this:
oddDigits :: Integer -> Bool
lst = []
oddDigits x
| (x < 0) || (x == 0) = error
| x `mod` 10 ++ lst ++ oddDigits(x `div` 10)
| length(lst) `mod` 2 /= 0 = True
| otherwise = False
Sorry if the code looks horrible. I am new to Haskell and still learning. What exactly am I doing wrong and how could I correct it?
First off, this seems a pretty weird thing to check. Perhaps what you're doing wrong is to ever consider this problem...
But if you persist you want to know the property of an integer having an odd number of digits... oh well. There's a lot that could be improved. For starters, (x < 0) || (x == 0) doesn't need the parentheses – < and == (infix 4) bind more tightly than ||. If you're not sure about this, you can always ask GHCi:
Prelude> :i ==
class Eq a where
(==) :: a -> a -> Bool
...
-- Defined in ‘GHC.Classes’
infix 4 ==
Prelude> :i ||
(||) :: Bool -> Bool -> Bool -- Defined in ‘GHC.Classes’
infixr 2 ||
But here you don't need || anyway because there's a dedicated operator for less-than-or-equal. Hence you can just write
oddDigits x
| x <= 0 = error "bla bla"
| ...
Then, you can “convert” the number to a string. Converting to string is generally a really frowned-upon thing to do because it throws all structure, typechecking etc. out of the window; however “number of digits” basically is a property of a string (the decimal expansion), rather than a number itself, so this is not entirely unsensible for this specific task. This would work:
oddDigits x
| x <= 0 = error "blearg"
| length (show x)`mod`2 /= 0 = True
| otherwise = False
however it's a bit redundancy department redundant. You're checking if something is True, then give True as the result... why not just put it in one clause:
oddDigits x
| x <= 0 = error "blearg"
| otherwise = length (show x)`mod`2 /= 0
That's perhaps in fact the best implementation.
For any proper, sensible task, I would not recommend going the string route. Recursion is better. Here's what it could look like:
oddDigits 1 = True
oddDigits x
| x <= 0 = error "blearg"
| otherwise = not . oddDigits $ x`div`10
There's nothing wrong with your general approach of converting to a list of digits, then finding the length of the list. Really where you went wrong is trying to cram everything into one function. As you found out first hand, it makes it very difficult to debug. Functional programming works best with very small functions.
If you separate out the responsibility of converting an integer to a list of digits, using a digs function like the one from this answer, the rest of your algorithm simplifies to:
oddDigits x | x <= 0 = error
oddDigits x = odd . length $ digs x
leftaroundabout's eventual answer is very nice, however it fails for numbers like 2,3 and 23. Here's a fix.
oddDigits x
| x <= 0 = error "blearg"
| x < 10 = True
| otherwise = not . oddDigits $ x`div`10
Its much more elegant than my initial answer, below. I'm including it to introduce a common functional paradigm, a worker/wrapper transformation of the problem. Here the wrapper gives the interface and passes off the work to another function. Notice that the negativity check only needs to be done once now.
oddDigits :: Integer -> Bool
oddDigits x
| x <= 0 = False
| otherwise = oddDigits' True x
oddDigits' :: Bool -> Integer -> Bool
oddDigits' t x
| x < 10 = t
| otherwise = oddDigits' (not t) $ x `div` 10
oddDigits' carries a piece of internal data with it, the initial Bool. My first first thought was to have that Bool be a digit accumulator, counting the number of digits. In that case, an "unwrapper" needs to be supplied, in this case the standard "odd" function:
oddDigits x
| x <= 0 = False
| otherwise = odd . oddDigits'' 1 $ x
where oddDigits'' :: Integer -> Integer -> Integer.

haskell add anything to a existing function

hey there using this script:
smallestDifference3 :: Int -> Int -> Int -> Int
smallestDifference3 a b c
| ((differenceAB < differenceBC) && (differenceBC < differenceAC)) = differenceAB
| ((differenceAB < differenceAC) && (differenceAC < differenceBC)) = differenceAB
| ((differenceBC < differenceAB) && (differenceAB < differenceAC)) = differenceBC
| ((differenceBC < differenceAC) && (differenceAC < differenceAB)) = differenceBC
| ((differenceAC < differenceBC) && (differenceBC < differenceAB)) = differenceAC
| ((differenceAC < differenceAB) && (differenceBC < differenceBC)) = differenceAC
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
i can type three Integers and get the smallest result of two of these Integer´s.
but what can i do if i add one more INT, so i have:
smallestDifference4 :: Int -> Int -> Int -> Int -> Int
smallestDifference4 a b c d
// etc..
Should i use the "smallestDifference3"-function to get this or what do i need to do? greetings!
Introduce a generic function which takes a list, i.e.
smallestDifference :: [Int] -> Int
and then use that from your other functions, e.g.
smallestDifference4 :: Int -> Int -> Int -> Int -> Int
smallestDifference4 a b c d = smallestDifference [a,b,c,d]
...of course, at that point you might want to just drop those tiny functions altogether since they don't "pull their own weight".
That being said, you could implement this function more in terms of existing functions. The idea is that you need a way to get all possible pairs for the given list, then compute the difference of the pair members, and then pick the minimum of that.
You would need an 'all pairs' function like
pairs :: [a] -> [(a, a)]
pairs = concat . go
where go [] = []
go [x] = []
go (x:xs) = map (\a -> (x,a)) xs : go xs
and then you could do it like
smallestDifference = minimum
. map abs
. map (uncurry (-))
. pairs

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!

Order-dependant Bit Fields

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.

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.