Why does the operator ** fail where the operator ^ works? - haskell

So, here are two list comprehensions, first uses ^ while second uses **:
> [x ^ 2 | x <- [1..10], odd x]
[1,9,25,49,81]
> [x ** 2 | x <- [1..10], odd x]
<interactive>:9:1:
No instance for (Show t0) arising from a use of ‘print’
The type variable ‘t0’ is ambiguous
Note: there are several potential instances:
instance Show Double -- Defined in ‘GHC.Float’
instance Show Float -- Defined in ‘GHC.Float’
instance (Integral a, Show a) => Show (GHC.Real.Ratio a)
-- Defined in ‘GHC.Real’
...plus 23 others
In a stmt of an interactive GHCi command: print it
As far as I know difference between the two operators is that first works with integers, while second works with floating point values. Expected output then:
[1.0,9.0,25.0,49.0,81.0]
Actual question is: why does the second list comprehension fail?

As you say ** works with floating ponints. However odd only works with Integrals. Therefore your second list comprehension only works with types that are instances of both Floating and Integral and such a type does not exist.
However I'm not sure why the error message claims that there are 26 possible instances when none of the instances it mentions actually meet the required constraints.

Related

Why does multiplesOf num max = [num*k | k <- [1..floor (max/num)]] throw an error?

I am trying to create a set of all the multiples of a number num under an upper limit max. I have written the following function in Haskell:
multiplesOf num max = [num*k | k <- [1..floor (max/num)]]
Why does this function throw the following error during run-time and how can it be fixed?
<interactive>:26:1: error:
• Ambiguous type variable ‘a0’ arising from a use of ‘print’
prevents the constraint ‘(Show a0)’ from being solved.
Probable fix: use a type annotation to specify what ‘a0’ should be.
These potential instances exist:
instance Show Ordering -- Defined in ‘GHC.Show’
instance Show Integer -- Defined in ‘GHC.Show’
instance Show a => Show (Maybe a) -- Defined in ‘GHC.Show’
...plus 22 others
...plus 18 instances involving out-of-scope types
(use -fprint-potential-instances to see them all)
• In a stmt of an interactive GHCi command: print it
This error was thrown when, for example, entering multiplesOf 3 1000.
There is no error in defining the function. The error is more when you want to use the function.
If we take a look at the type of the function you have constructed, we see:
multiplesOf :: (RealFrac t, Integral t) => t -> t -> [t]
So here the type of input and output values should both be Integral, and RealFrac. So that means that number should be Integral, but at the same time support real division. There are not much types that would fit these requirements.
This problem arises from the fact that you use (/) and floor here, which hints that max and num are RealFracs, but the result of floor is an Integral, and then you mulitply numbers out of this range again with num.
You can however reduce the amount of type constraints, by making use of div :: Integral a => a -> a -> a. This is thus integer division, and the result is truncated towards negative infinity, so we can implement the function like:
multiplesOf :: Integral i => i -> i -> [i]
multiplesOf num max = [num*k | k <- [1..div max num]]
or we can even save us the trouble of making divisions, multiplications, etc. and work with a range expression that does the work for us:
multiplesOf :: (Num n, Enum n) => n -> n -> [n]
multiplesOf num max = [num, (num+num) .. max]
The latter is even less constraint, since Integral i implies Real i and Enum i.

Haskell - Signature and Type error

I'm new to Haskell and I'm having some trouble with function signature and types. Here's my problem:
I'm trying to make a list with every number between 1 and 999 that can be divided by every numeral of it's own number. For example the number 280 can be in that list because 2+8+0=10 and 280/10 = 28 ... On the other hand 123 can't because 1+2+3=6 and 123/6=20,5. When the final operation gives you a number with decimal it will never be in that list.
Here's my code:
let inaHelper x = (floor(x)`mod`10)+ (floor(x/10)`mod`10)+(floor(x/100)`mod`10)
This first part will only do the sum of every numeral of a number.
And this part works...
Here's the final part:
let ina = [x | x <- [1..999] , x `mod` (inaHelper x) == 0 ]
This final part should do the list and the verification if it could be on the list or not. But it's give this error:
No instance for (Integral t0) arising from a use of ‘it’
The type variable ‘t0’ is ambiguous
Note: there are several potential instances:
instance Integral Integer -- Defined in ‘GHC.Real’
instance Integral Int -- Defined in ‘GHC.Real’
instance Integral Word -- Defined in ‘GHC.Real’
In the first argument of ‘print’, namely ‘it’
In a stmt of an interactive GHCi command: print it
...
ina = [x | x <- [1..999] , x `mod` (inaHelper x) == 0 ]
What is the type of x? Integer? Int? Word? The code above is very generic, and will work on any integral type. If we try to print its type we
get something like this
> :t ina
ina :: (Integral t, ...) => [t]
meaning that the result is a list of any type t we want, provided t is an integral type (and a few other constraints).
When we ask GHCi to print the result, GHCi needs to choose the type of x, but can not decide unambiguously. This is what the error message states.
Try specifying a type when you print the result. E.g.
> ina :: [Int]
This will make GHCi choose the type t to be Int, removing the ambiguity.

Ambiguous type variable `a0' arising from a use of `print'?

While learning Haskell I'm trying to write a function that given a number will give its successor in a Collatz sequence:
next :: (Fractional a, Integral a) => a -> a
next x
| odd x = x * 3 + 1
| otherwise = x / 2
When I run next 7 I get:
<interactive>:150:1: error:
* Ambiguous type variable `a0' arising from a use of `print'
prevents the constraint `(Show a0)' from being solved.
Probable fix: use a type annotation to specify what `a0' should be.
These potential instances exist:
instance Show Ordering -- Defined in `GHC.Show'
instance Show Integer -- Defined in `GHC.Show'
instance Show a => Show (Maybe a) -- Defined in `GHC.Show'
...plus 22 others
...plus 12 instances involving out-of-scope types
(use -fprint-potential-instances to see them all)
* In a stmt of an interactive GHCi command: print it
Two questions:
Am I using the best class constraints in my signature?
Assuming I am, how can I show the result of next 7 ?
I believe Collatz sequence is an integer sequence, so it wouldn't be necessary making the result Fractional.
next :: (Integral a) => a -> a
To be able to get an integer from a division, you should use div function. Note that division will always be exact as you are going to divide only even numbers:
next x
| odd x = x * 3 + 1
| otherwise = x `div` 2

Show list of unknown type in Haskell

I was given an assignment in which I should have the type signature
Group g => Int -> Int -> [[g]]
However if g is ambiguous how can I print it? I get this error:
No instance for (Show g0) arising from a use of ‘print’
The type variable ‘g0’ is ambiguous
Note: there are several potential instances:
instance Show Double -- Defined in ‘GHC.Float’
instance Show Float -- Defined in ‘GHC.Float’
instance (Integral a, Show a) => Show (GHC.Real.Ratio a)
-- Defined in ‘GHC.Real’
...plus 24 others
In the expression: print
In the expression: print $ myTest 10 0
In an equation for ‘main’: main = print $ myTest 10 0
Which makes sense to me. Is there an error in the assignment? Or is there a way to print an ambiguous type?
Try running
> :info Group
This should print out the Group typeclass and its members, followed by a list of instances. Pick one of these instances, then execute
> myTest 1 2 :: [[TheTypeYouPicked]]
If you wanted to use it inside main you'll have to give it a type signature there too:
main :: IO ()
main = print (myTest 10 0 :: [[TheTypeYouPicked]])
The reason why the compiler is showing you this error is because there could be many instances of Group to choose from, not all of them necessarily implement Show as well. In order to print something in the console, either by just executing it (there's an implicit print when you just run a normal function in GHCi) or with an explicit print it needs to implement Show.

How and why is [1 .. 0] different from [1 .. -1] in Haskell?

I have defined the following function
let repl x n = [x | _ <- [1..n]]
which imitates the built-in replicate function.
While experimenting with it, I noticed a strange thing: repl 10 0 evaluates to [], while repl 10 -1 produces an error:
No instance for (Show (t10 -> [t0])) arising from a use of ‘print’
In a stmt of an interactive GHCi command: print it
On the other hand, both [1 .. 0] and [1 .. -1] evaluate to [] without producing any errors.
Moreover, both [42 | _ <- [1 .. 0]] and [42 | _ <- [1 .. -1]] evaluate to [] without errors.
So why does my function call result in an error where the explicit substitution doesn't? And more importantly, where does the apparent difference between [1 .. 0] and [1 .. -1] stem from?
And a final question: when I write:
repl 42 -1
the error is exactly the same as with repl 10 -1, i.e. it still has the (Show (t10 -> [t0])) bit in it. I was expecting it to have something like ((Show (t42 -> [t0]))). What's this 10?
Other answers have pointed out that you need to wrap -1 in parentheses. This is an odd corner of the Haskell 98 spec that jumps out to bite unexpectedly. It's not the case that you can never write a negative number without parentheses: -1 * 5 is fine. It's just that the unary prefix operator doesn't have higher precedence than the binary infix operator, so a - is frequently parsed as the latter. Whitespace around operators is not significant in Haskell.
And the incomprehensible typeclass error doesn't help. Incidentally, t10 and t0 are just placeholder type variables made up by the compiler; I don't think it has anything to do with the actual numeric literals you use. And informally, errors like Could not deduce (Num (a0 -> t)) usually indicate to me that a function is applied to too few arguments.
Alternatively, the (undocumented?) NegativeLiterals language extension in GHC 7.8 changes the meaning of -1 to address this problem.
> :set -XNegativeLiterals
> :t repl 10 -1
repl 10 -1 :: Num t => [t]
You have not included the full error message in your question, and if you had, you'd see that repl 10 -1 is parsed as (repl 10) - (1) which is not what you intended.
You'd get the same error with repl 10 +1.
You can often find clues as to how a program code is parsed, by looking closely into the error message. There's no harm in overusing parentheses, while you learn, either.
The program:
repl x n = [x | _ <- [1..n]] -- line 1
main = print (repl 10 -1) -- line 3
The message:
prog.hs:3:8:
No instance for (Show (t1 -> [t0])) arising from a use of `print'
Possible fix: add an instance declaration for (Show (t1 -> [t0]))
In the expression: print (repl 10 - 1)
In an equation for `main': main = print (repl 10 - 1)
prog.hs:3:15:
No instance for (Num t1) arising from a use of `repl'
The type variable `t1' is ambiguous
Possible fix: add a type signature that fixes these type variable(s)
Note: there are several potential instances:
instance Num Double -- Defined in `GHC.Float'
instance Num Float -- Defined in `GHC.Float'
instance Integral a => Num (GHC.Real.Ratio a)
-- Defined in `GHC.Real'
...plus three others
In the first argument of `(-)', namely `repl 10' --------- NB!
In the first argument of `print', namely `(repl 10 - 1)'
In the expression: print (repl 10 - 1)
prog.hs:3:20:
No instance for (Num t0) arising from the literal `10'
The type variable `t0' is ambiguous
Possible fix: add a type signature that fixes these type variable(s)
Note: there are several potential instances:
instance Num Double -- Defined in `GHC.Float'
instance Num Float -- Defined in `GHC.Float'
instance Integral a => Num (GHC.Real.Ratio a)
-- Defined in `GHC.Real'
...plus three others
In the first argument of `repl', namely `10'
In the first argument of `(-)', namely `repl 10' --------- NB!
In the first argument of `print', namely `(repl 10 - 1)'
prog.hs:3:23:
No instance for (Num (t1 -> [t0])) arising from a use of `-'
Possible fix: add an instance declaration for (Num (t1 -> [t0]))
In the first argument of `print', namely `(repl 10 - 1)'
In the expression: print (repl 10 - 1)
In an equation for `main': main = print (repl 10 - 1)
Did you try [1..(-1)]? In Haskell, you cannot write negative numbers like -1 directly. You need to put them in parentheses. The reason is that Haskell doesn't have prefix unary operators because operators in Haskell are always infix. Hence -1 is parsed as [operator (-)] [numeric 1] and not [numeric -1].
This is what causes the problem. To avoid this problem, negative numbers must always be put in parentheses. This ensures that (-1) is parsed as [numeric -1]. It's one of the few corner cases which gives migraines to newcomers in Haskell.

Resources