Haskell. Matching pattern Problem. Cannot put in IO value of function with empty list "print $ note1 []" - failing to compile - haskell

Haskell. Matching pattern Problem. Cannot put in IO value of function with empty list
print $ note1 []
failing to compile, but works fine in ghci ?!
Also the print $ note1 [1] works fine and compiles fine too. The problem only with empty list:
print $ note1 []
(N.B. I am new in Haskell)
I
have a matching pattern function
note1 :: (Show a) => [a] -> String
note1 [] = "Empty"
note1 (x:[]) = "One"
But print $ note1 [] fails to compile, but perfectly works in ghci interpreter?!
I am using stack 2.3.1 and ghc 8.8.3 on MacOS.
This is the compilation error produced by compiler.
/Users/admin1/Haskell/PROJECTS/orig1/src/Lib.hs:18:13: error:
• Ambiguous type variable ‘a0’ arising from a use of ‘note1’
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 15 instances involving out-of-scope types
(use -fprint-potential-instances to see them all)
• In the second argument of ‘($)’, namely ‘note1 []’
In a stmt of a 'do' block: print $ note1 []
In the expression:
do putStrLn "someFunc"
putStrLn $ show (1)
putStrLn $ show $ length ("a" :: String)
putStrLn $ show (length' "a")
.... |
18 | print $ note1 []

The problem is the (unnecessary, in this case) Show a constraint on note1. Here's what happens. When GHC is typechecking print $ note1 [], it needs to work out which Show instance to use with note1. That's typically inferred from the type of elements in the list that it's passed. But the list it's passed ... doesn't have any elements. So the typechecker has no particular way to choose an instance, and just gives up. The reason this works in GHCi is that GHCi, by default, enables the ExtendedDefaultRules language extension, which expands the type defaulting rules. So instead of throwing up its hands, the type checker picks the type () for elements of the list, and everything works. Something sort of similar is going on when you use [1]. In that case, the standard defaulting rule comes into play: numeric types default to Integer, so the typechecker picks that type.
How should you fix this? You could manually write
print $ note1 ([] :: [()])
to make your code compile, but if that's your real code, you'd be much better off removing the unnecessary constraint:
note1 :: [a] -> String
note1 [] = "Empty"
note1 (x:[]) = "One"
As a side note, since you don't use the x variable, it's best to make that fact explicit by either using the special _ pattern:
note1 :: [a] -> String
note1 [] = "Empty"
note1 (_:[]) = "One"
or prefixing the variable name with an underscore:
note1 :: [a] -> String
note1 [] = "Empty"
note1 (_x:[]) = "One"
This indicates, both to other programmers (such as yourself a few hours later) and the compiler, that you are intentionally not using that value.
Additionally, you can (and probably should) use list syntax to clarify the second pattern:
note1 [_] = "One"
Finally, the note1 function has a bit of a problem: if you pass it a list with more than one element, it'll produce a pattern match failure. Whoops! It's usually better to write total functions when you can. When you can't, it's generally best to use an explicit error call to indicate what went wrong. I recommend compiling your code with the -Wall flag to help catch mistakes.

Related

Why such different behaviour with `Ambiguous type..` error (in ghci)?

This example works with ghci, load this file:
import Safe
t1 = tailMay []
and put in ghci:
> print t1
Nothing
But if we add analogous definition to previous file, it doesn't work:
import Safe
t1 = tailMay []
t2 = print $ tailMay []
with such 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
That is 3rd sample for ghc with the same error:
import Safe
t1 = tailMay
main = do
print $ t1 []
print $ t1 [1,2,3]
Why? And how to fix the second sample without explicit type annotation?
The issue here is that tailMay [] can generate an output of type Maybe [a] for any a, while print can take an input of type Maybe [a] for any a (in class Show).
When you compose a "universal producer" and a "universal consumer", the compiler has no idea about which type a to pick -- that could be any type in class Show. The choice of a could matter since, in principle, print (Nothing :: Maybe [Int]) could print something different from print (Nothing :: Maybe [Bool]). In this case, the printed output would be the same, but only because we are lucky.
For instance print ([] :: [Int]) and print ([] :: [Char]) will print different messages, so print [] is ambiguous. Hence, GHC reject it, and requires an explicit type annotation (or a type application # type, using an extension).
Why, then, such ambiguity is accepted in GHCi? Well, GHCi is meant to be used for quick experiments, and as such, as a convenience feature, it will try hard to default these ambiguous a. This is done using the extended defaulting rules, which could (I guess) in principle be turned on in GHC as well by turning on that extension.
This is, however, not recommended since sometimes the defaulting rule can choose some unintended type, making the code compile but with an unwanted runtime behavior.
The common solution to this issue is using an annotation (or # type), because it provides more control to the programmer, makes the code easier to read, and avoids surprises.

Haskell basic Show instance for simple recursive datatype not working

i have a simple Problem. This Code looks perfectly fine to me.
main = do
print("10-2")
let a = L
let b = E "abc" a
print(a)
print(b)
data List a = L | E a (List a)
instance (Show a) => Show (List a) where
show L = "Empty"
show (E a list) = (show a)++ (show list)
But it produces following error:
10-2.hs:5:5:
No instance for (Show a0) arising from a use of `print'
The type variable `a0' is ambiguous...
I cant find the Problem. Thanks for the Help!
It's the same error you will get if you try to compile this simple program:
main = print []
What? Haskell cannot print an empty list? That's correct, it cannot. That is, unless the type of the list element is known. It is not known at this case, so compilation fails. In order to see why, run these two programs:
main = print ([] :: [Int])
main = print ([] :: [Char])
The output is different, though the only difference between these programs is the type of an empty list.
However, if you try this same ambiguous program in ghci it will print [] just fine!
Prelude> let main = print []
Prelude> main
[]
Prelude>
This is because ghci has a slightly more liberal set of defaulting rules than ghc. So if you load your data type definition to ghci and say print L at the prompt, ghci will happily obey:
[1 of 1] Compiling Main ( h.hs, interpreted )
Ok, modules loaded: Main.
*Main> print L
Empty
*Main>
In your function main, when you write let a = L, the type of a is just List a0. When the compiler tries to know which version of the Show instance it has to use, all types fits, because a's type is not fully defined. If you delete the line print a however, you will see that print b will work, because b's type can only be List String, and the compiler knows exactly which version of show it has to use.
main = do
print "10-2"
let a = L
let b = E "abc" a
-- print a
print b
Try writing print [] and you will see that the compiler gives you the same kind of error.
In ghci however, if you just type print L or print [], it will not prompt an error. I don't know why this is happening.
As the others already said, you need to give your List a type, even if the data Constructor doesn't need it to create itself.
So Try out:
print (L :: List Int)
or whatever you like to just print a your String of the Show Instance of (List a)

No instance for Num String arising from the literal `1'

main = do
putStrLn $myLast [1,2,3,4]
myLast :: [a] -> a
myLast [x] = x
myLast (_:xs) = myLast xs
When i try to run this code i get this message:
"No instance for (Num String) arising from the literal `1'
Possible fix: add an instance declaration for (Num String)"
It runs well when I run with the list ["1","2","3,"4"]. I didn't specify the type but it doesn't work with ints.
"No instance for..." error messages are usually misleading.
The problem you have is simply this
Prelude> :t putStrLn
putStrLn :: String -> IO ()
i.e. that function can only deal with strings, not with numbers. An often-seen solution is to first translate the thing you want to show into a string: putStrLn (show x), but actually the combination exists as a much nicer standard function:
main = do
print $ myLast [1,2,3,4]
The compiler concludes from
putStrLn x
that x must be a String. The inferred type for
myLast [1,2,3,4]
is Num a => a and when you now substitute a with String you get
Num String => String
This is all quite logical, except that the type checker remembers that the Num constraint originated from the literal 1.
The message you get is thus just another way to say that a number is not a string, and putStrLn badly wants a string. Or, if you want, that the expression would be well typed, if only strings were numbers.
putStrLn has type String -> IO () so you need to convert your list element into a string first.
You can do this with show:
putStrLn $ show $ myLast [1,2,3,4]

No instance for (Show a0) arising from a use of `print' The type variable `a0' is ambiguous

data NestedList a = Elem a | List [NestedList a]
flatten :: NestedList a -> [a]
flatten (Elem element) = [element]
flatten (List []) = []
flatten (List (first:rest)) = flatten first ++ flatten (List (rest))
main = print $ flatten $ List []
I wrote the above seen code in haskell. When I execute this with any other parameter, for example
main = print $ flatten $ List [Elem 1, Elem 2]
main = print $ flatten $ Elem 1
It gives
[1, 2]
[1]
respectively.
It fails when I execute it with an empty List.
main = print $ flatten $ List []
Error message
No instance for (Show a0) arising from a use of `print'
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 23 others
In the expression: print
In the expression: print $ flatten $ List []
In an equation for `main': main = print $ flatten $ List []
Questions
Why does it fail and how can I fix this?
Should I change my NestedList definition to accept an empty List? If so, how do I do that. Its quite confusing.
The list type is polymorphic. Since you don't supply an element, just the empty list constructor [], there's no way to infer what list type this is.
Is it: [] :: [Int]
or [] :: [Maybe (Either String Double)]. Who's to say?
You are. Supply a type annotation to resolve the polymorphism, then GHC can dispatch to the correct show instance.
E.g.
main = print $ flatten $ List ([] :: [Int])
To add to the answers here already, you may object "but what does it matter what type of things my list contains? it doesn't have any of them in it!"
Well, first of all, it is easy to construct situations in which it's unclear whether or not the list is empty, and anyway type checking hates to look at values, it only wants to look at types. This keeps things simpler, because it means that when it comes to deal with values, you can be sure you already know all the types.
Second of all, it actually does matter what kind of list it is, even if it's empty:
ghci> print ([] :: [Int])
[]
ghci> print ([] :: [Char])
""
The problem is the compiler can't know the type of flatten $ List []. Try to figure out the type yourself, you'll see it's [a] for some a, whilst print requires its argument to be an instance of Show, and [a] is an instance of Show if a is an instance of Show. Even though your list is empty, so there's no need for any constraint on a to represent [], there's no way for the compiler to know.
As such, putting an explicit type annotation (for any type for which an instance of Show exists) should work:
main = print $ flatten $ List ([] :: [NestedList Int])
or
main = print $ flatten $ List ([] :: [NestedList ()])
or
main = print fl
where
fl :: [()]
fl = flatten $ List []
[] can be a list of floats, strings, booleans or actually any type at all. Thus, print does not know which instance of show to use.
Do as the error message says and give an explicit type, as in ([] :: [Int]).

GHCI can't infer Eq class at compile time, but does fine at runtime?

Sorry for the confusing title. I am writing a parser combinator library in Haskell for fun. Here are all (I think!) the relevant type annotations and definitions:
data Parser a = Parser (State -> Reply a)
parse :: Parser a -> [Char] -> Either ParseError a
nil :: Parser [a]
nil = Parser $ \state -> Ok [] state
Basically, the parse function applies the function that a Parser wraps around to the current state, and if the parse is successful, wraps the result in an Either. The nil parser takes a state and returns a successful parse of the empty list. So we should have,
parse nil "dog" == Right []
In fact, if I just load the module where all these live, then it compiles and this evaluates to True.
I'm actually trying to run some QuickCheck tests on the library, though, so I wrote this:
import Parsimony
import Test.QuickCheck
prop_nil :: [Char] -> Bool
prop_nil xs = parse nil xs == Right []
This fails to compile! It throws the following error:
No instance for (Eq a0) arising from a use of `=='
The type variable `a0' is ambiguous
At this point I am mostly just confused why an expression could work fine when evaluated, but fail to compile in a parametrized version.
Since nil is polymorphic and Right [] is also polymorphic GHC has an expression of type Bool, but with some unbound type variable in the middle. GHC keels over and dies since it doesn't know what concrete type to use. GHCi for better or worse, will infer [()] or something like that because of its defaulting rules. This is one of ghci's weird quirks, it will automagically default type variables.
To fix this, simply for force the binding of a manually
-- It's important that whatever you force it to actually is comparable
-- eg there should be an instance like
instance Eq ParseError where
-- Otherwise you're kinda stuck.
prop_nil xs = parse nil xs == (Right xs :: Either ParseError String)
PS I like the name Parsimony for a parser library, good luck!
The problem is that the type of nil is Parser [a]. So parse nil xs is of type Either ParseError [a]. Right [] is most generally of type Either l [a]; comparing it to parse nil xs forces the l to be ParseError, but the type in the list is still completely unconstrained. Without any more context it remains fully polymorphic; that a isn't necessarily a member of the Eq type class and even if it is there's no way to know which instance to use for the implementation of ==, and so it isn't valid to invoke == on those two terms.
In a realistic program, you'd likely be saved from this by the fact that you'd use the result for something, which would force that particular occurrence to be consistent with whatever you use it for. That would probably be some concrete type which has an implementation of Eq.
When you talk about loading the module, I presume you mean in the GHCI interpreter. GHCI adds some additional defaulting rules. In particular it will tend to default unconstrained type variables (which aren't the type of a top level function) to (), so that it doesn't have to complain about ambiguous type variables quite so often.
An interactive session in GHCi tends to encounter ambiguous type variable far more often than realistic modules compiled in full, because it has to compile small snippets mostly independently. GHCi has extended defaulting rules to make those work a lot more often (though it often only delays the error to the next reference when the user was expecting a different type, and the difference between GHCi and GHC often causes confusion).
Test snippets can suffer from a similar problem. If you're testing polymorphic functions you often don't constrain some of the types sufficiently for type inference to work, as you would in real purposeful usage of the function. But without the extended defaulting rules of GHCi, this problem manifests as an actual ambiguous type error at the location of the problem, rather than masking it by arbitrarily picking a type.
To fix this, you just need to add a type annotation to fix the type of the list. Either declare the full type of parse nil xs or Right [], just declare the type of the empty list literal on the right hand side. Sometihng like this should do the trick:
prop_nil :: [Char] -> Bool
prop_nil xs = parse nil xs == Right ([] :: [Int])
Another way would be to avoid the Eq constraint in the first place:
prop_nil xs = either (const False) null (parse nil xs)
or, more explicit
prop_nil xs = case parse nil xs of
Right [] -> True
_ -> False

Resources