Show list of unknown type in Haskell - 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.

Related

Show Constraint type in haskell

I am trying to use show function to print to the console value of zer or one, but I can not do it. Here is my code:
{-# LANGUAGE NoMonomorphismRestriction #-}
import Control.Arrow
import Data.List
import qualified Data.Map as M
import Data.Function
class Eq a => Bits a where
zer :: a
one :: a
instance Bits Int where
zer = 0
one = 1
instance Bits Bool where
zer = False
one = True
instance Bits Char where
zer = '0'
one = '1'
I am trying to use function show to convert zer or one to the string.
So I tried it:
k = zer
show k
but I got this error
<interactive>:10:1: error:
• Ambiguous type variable ‘a0’ arising from a use of ‘show’
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 k, Show a) => Show (M.Map k a)
-- Defined in ‘containers-0.5.7.1:Data.Map.Base’
instance Show Ordering -- Defined in ‘GHC.Show’
instance Show Integer -- Defined in ‘GHC.Show’
...plus 24 others
...plus 11 instances involving out-of-scope types
(use -fprint-potential-instances to see them all)
• In the expression: show zer
In an equation for ‘it’: it = show zer
so i tried to create instance for show. So I added this to my code:
instance (Show a) => Show (Bits a) where
show zer = "0"
show one = "1"
But I got another error
main.hs:25:28: error:
• Expected a type, but ‘Bits a’ has kind ‘Constraint’
• In the first argument of ‘Show’, namely ‘Bits a’
In the instance declaration for ‘Show (Bits a)’
Can you tell me what I am doing wrong?
You're trying to make a class an instance of a class, rather than making a type an instance of a class. Compare:
Show a => Show (Bits a) -- Invalid
to
Show a => Show (Maybe a) -- Valid
where Maybe is a datatype whereas Bits is a class name.
I don't think it's possible to express "anything that has a Bits instance has a Show instance", because it can lead to overlapping instances: if you could define something like that, then when you use show :: Int -> String the compiler wouldn't know whether to use the Prelude's instance of Show Int or the show that would be defined by Int being an instance of Bits.
A messy workaround could be to enforce "the other direction": that every instance of Bits must be an instance of Show, which would allow you to use a's Show instance rather than your own one:
class (Show a, Eq a) => Bits a where
zer :: a
one :: a
main = print (zer :: Int)
although this requires an explicit type signature to resolve the ambiguity in the type of zer at the call site.

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.

In GHCi, why can't I show `pure 1` in REPL?

I tried to assign a lifted value to a.
λ> :m Control.Applicative
λ> let a = pure 1
When I evaluated a in REPL, it prints 1.
λ> a
1
Therefore, I thought there may be an implementation of show for a, and tried this:
λ> show a
But the GHCi throws an error:
<interactive>:70:1-4:
No instance for (Show (f0 a0)) arising from a use of ‘show’
The type variables ‘f0’, ‘a0’ are ambiguous
Note: there are several potential instances:
instance (Integral a, Show a) => Show (GHC.Real.Ratio a)
-- Defined in ‘GHC.Real’
instance (Show a, Show b) => Show (a, b) -- Defined in ‘GHC.Show’
instance (Show a, Show b, Show c) => Show (a, b, c)
-- Defined in ‘GHC.Show’
...plus 32 others
In the expression: show a
In an equation for ‘it’: it = show a
Does anyone have any ideas about this?
GHCi is defaulting the Applicative f => f to IO. When you do
λ> a
1
you actually run an IO Integer action such as
λ> let a = return 1
λ> a
1
GHCi by default prints the result of IO actions. Hence the 1 in the result line. (Quite confusingly, this 1 is not the value of a, nor the output of running a as an IO action -- just the returned value of the latter.)
GHCi uses a sophisticated heuristics to handle user input. First, it tries to show it, possibly defaulting some type classes like numeric ones. This fails in your case. When that fails, it tries to see if the input is an IO action. In such case, the action is run and, if the result can be showed, it is printed.
Note that this GHCi magic only happens at the top level.
When you try to show a, GHCi tries its magic on the whole show a, not on a, so the same effect does not happen.

Generating a list of random values and printing them to standard output in Haskell

I am pretty new to Haskell and I am struggling to achieve something relatively simple: to generate a list of random numbers and print them to standard output.
Since the random concept is pretty contrary to the function purity in FP world (i.e. methods should return always the same result for the same input), I understand that in this case, the System.Random module in Haskell returns IO actions instead.
My code so far looks like the following:
import System.Random
randomNumber :: (Random a) => (a, a) -> IO a
randomNumber (a,b) = randomRIO(a,b)
main :: IO ()
main = do
points <- sequence (map (\n -> randomNumber ((-1.0), 1.0)) [1..10])
print points
The idea is simple: to generate a list of ten random elements (probably there are better ways to achieve that). My first approach has been creating a function that returns a random number (randomNumber in this case, of type IO a) and using it when mapping over a list of elements (producing a list of IO actions, IO [a]).
From my understanding, sequence (map (\n -> randomNumber ((-1.0), 1.0)) [1..10]) type is IO [a] but I do not know how I can use it. How can I really use points as some value of type [a] instead of IO [a]?
EDIT: Adding the print function within the do "block" produces some errors I don't really know how to get rid of.
Main.hs:8:40:
No instance for (Random a0) arising from a use of ‘randomNumber’
The type variable ‘a0’ is ambiguous
Note: there are several potential instances:
instance Random Bool -- Defined in ‘System.Random’
instance Random Foreign.C.Types.CChar -- Defined in ‘System.Random’
instance Random Foreign.C.Types.CDouble
-- Defined in ‘System.Random’
...plus 33 others
In the expression: randomNumber ((- 1.0), 1.0)
In the first argument of ‘map’, namely
‘(\ n -> randomNumber ((- 1.0), 1.0))’
In the first argument of ‘sequence’, namely
‘(map (\ n -> randomNumber ((- 1.0), 1.0)) [1 .. 10])’
Main.hs:8:55:
No instance for (Num a0) arising from a use of syntactic negation
The type variable ‘a0’ is ambiguous
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 37 others
In the expression: (- 1.0)
In the first argument of ‘randomNumber’, namely ‘((- 1.0), 1.0)’
In the expression: randomNumber ((- 1.0), 1.0)
Main.hs:8:56:
No instance for (Fractional a0) arising from the literal ‘1.0’
The type variable ‘a0’ is ambiguous
Note: there are several potential instances:
instance Fractional Double -- Defined in ‘GHC.Float’
instance Fractional Float -- Defined in ‘GHC.Float’
instance Integral a => Fractional (GHC.Real.Ratio a)
-- Defined in ‘GHC.Real’
...plus three others
In the expression: 1.0
In the expression: (- 1.0)
In the first argument of ‘randomNumber’, namely ‘((- 1.0), 1.0)’
Main.hs:9:9:
No instance for (Show a0) arising from a use of ‘print’
The type variable ‘a0’ is ambiguous
Relevant bindings include points :: [a0] (bound at Main.hs:8:9)
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 65 others
In a stmt of a 'do' block: print points
In the expression:
do { points <- sequence
(map (\ n -> randomNumber ((- 1.0), 1.0)) [1 .. 10]);
print points }
In an equation for ‘main’:
main
= do { points <- sequence
(map (\ n -> randomNumber ((- 1.0), 1.0)) [1 .. 10]);
print points }
Failed, modules loaded: none.
Why does this happen?
There is one particular message in all your errors: The type variable ‘a0’ is ambiguous. Why is this the case? Well, randomNumber works for any instance of Random, and there are a bunch of instances. -1.0 includes Num, since you want to be able to negate a value. Also, the value 1.0 itself concludes that your type needs to be an instance of Fractional. That reduces the amount of types that can be used in this circumstance, but it's still not unique: Float, Double and four others are suitable.
At this point, the compiler gives up, and you need to tell it what instance you actually want to use.
How to fix this
There are many ways to fix this. For one, we could introduce a small helper function:
-- fix a to double
randomDouble :: (Double, Double) -> IO Double
randomDouble = randomNumber
Or we could annotate the type of the ambiguous 1.0:
points <- sequence (map (\n -> randomNumber ((-1.0), 1.0 :: Double)) [1..10])
-- ^^^ as a Double
Or we could annotate the type of the list:
print (points :: [Double])
-- ^^^^^^^^^^^^^^^^^^ points is a list of Doubles
Which one you choose is actually more or less a matter of style and personal preference. That being said, sequence . map f $ xs can be written as mapM f xs, but since you actually have IO a, you're better of with replicateM $ randomNumber (...). Both mapM and replicateM can be found in Control.Monad.
TL;DR
When GHC yells at you for ambiguous types, annotate them.
A couple points:
You called the function randomNumber, but allowed it to take any type that is a part of the Random class (including Chars etc.). If you do only want it to take numbers, you should change the signature to match its purpose (randomNumber :: (Int,Int) -> IO Int) or more generically, randomNumber :: (Num n. Random n) => (n,n) -> IO n
sequence takes a list of actions ([IO a]), and returns a list in the IO monad (IO [a]). It basically just executes each action, stores the result, then re-wraps the list in IO. You could try something like replicateM 10 $ randomNumber (1,10). replicateM takes an Int and an action to carry out, and returns a list of executed actions (as Zeta pointed out, sequence is used internally in a call to replicateM).
(And code blocks aren't working for me for some reason, so I wrote everything as "infix code".)

Error while compiling print Either value

I'm trying to compile simple code snippet.
main = (putStrLn . show) (Right 3.423)
Compile results in the following error:
No instance for (Show a0) arising from a use of `show'
The type variable `a0' is ambiguous
Possible fix: add a type signature that fixes these type variable(s)
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 42 others
In the second argument of `(.)', namely `show'
In the expression: putStrLn . show
In the expression: (putStrLn . show) (Right 3.423)
When i execute same snippet from ghci everything works as expected.
Prelude> let main = (putStrLn . show) (Right 3.423)
Prelude> main
Right 3.423
So the question is what is going on?
The problem is that GHC can't determine what the full type of Right 3.423 is, it can only determine that it has the type Either a Double, and the instance of Show for Either looks like instance (Show a, Show b) => Show (Either a b). Without that extra constraint on Either a Double, GHC doesn't know how to print it.
The reason why it works in interactive mode is because of the dreaded monomorphism restriction, which makes GHCi more aggressive in the defaults it chooses. This can be disabled with :set -XNoMonomorphismRestriction, and that is going to become the default in future versions of GHC since it causes a lot of problems for beginners.
The solution to this problem is to put a type signature on Right 3.423 in your source code, like
main = (putStrLn . show) (Right 3.423 :: Either () Double)
Here I've just used () for a, since we don't care about it anyway and it's the "simplest" type that can be shown. You could put String or Int or Double or whatever you want there, so long as it implements Show.
A tip, putStrLn . show is exactly the definition of print, so you can just do
main = print (Right 3.423 :: Either () Double)
As #ØrjanJohansen points out, this is not the monomorphism restriction, but rather the ExtendedDefaultRules extension that GHCi uses, which essentially does exactly what I did above and shoves () into type variables to make things work in the interactive session.

Resources