No instance for (Show ([(Char, Char)] -> Char)) - haskell

So I have to make a function that finds a pair with its 1st letter and returning the 2nd letter.
I actually found one answer but with the map function and I couldn't get it.
lookUp :: Char -> [(Char, Char)] -> Char
lookUp x [] = x
lookUp x ( ( st,nd ): rst) | st == x = nd
| otherwise = lookUp x rst
And I get this message:
No instance for (Show ([(Char, Char)] -> Char))
arising from a use of `print'
Possible fix:
add an instance declaration for (Show ([(Char, Char
In a stmt of an interactive GHCi command: print it

Your code is fine, you just need to supply all the arguments at the ghci prompt, eg
lookUp 'c' [('b','n'), ('c','q')]
Should give you 'q'.
It's complaining that it can't show a function. Any time it says it doesn't
have a Show instance for something with -> in, it's complaining it can't
show a function. It can only show the result of using the function on some data.
When you give it some, but not all data, Haskell interprets that as a new function
that takes the next argument, so
lookUp 'c'
is a function that will take a list of pairs of characters and give you a character.
That's what it was trying to show, but couldn't.
By the way, almost every time you get a "No instance for..." error, it's because
you did something wrong with the arguments - missed some out, put them in
the wrong order. The compiler's trying to be helpful by suggesting you add
an instance, but probably you just need to check you supplied the write type
of arguments in the right order.
Have fun learning Haskell!

It seems that you typed something like this in ghci:
*Main> lookUp 'c'
An expression like lookUp 'c' is a partial evaluation / curried form of the lookUp function. It's type is:
*Main> :t lookUp 'c'
lookUp 'c' :: [(Char, Char)] -> Char
which is the exact type that ghci says there is no Show instance for.
To test your function, be sure to supply both x and the the list of Char pairs:
*Main> lookUp 'c' [ ('a','A'), ('b','B'), ('c','C') ]
'C'

Related

Creating a conditioned Arbitrary instance ( * Ambiguous type variable `a' arising from a use of `quickCheck')

I have this test I want to make:
prop_inverse_stringsToInts st = isDigitList st ==> st == map show (stringsToInts st)
Which is testing a function that converts a list of Strings to a list of Integers, but of course the strings need to be digits so I created a pre-condition that checks that using the isDigitList function I made, but the condition is too specific and quickCheck gives up : "*** Gave up! Passed only 43 tests; 1000 discarded tests."
So I wanted to create an Arbitrary instance for my case, but the thing is I am inexperienced with working with Arbitrary, so I don't really know how to do this and every time I shuffle code I get a new error. All I want is an Arbitrary that only returns the Foo [String] if it passes the isDigitList (which receives a [String] and returns a Bool). So far I have something like this :
Foo a = Foo [String] deriving (Show,Eq)
instance (Arbitrary a) => Arbitrary (Foo a ) where
arbitrary = do
st <- (arbitrary :: Gen [String])
if isDigitList st
then do return (Foo st)
else do return (Foo []) -- This is probably a bad idea
I altered my property to :
prop_inverse_stringsToInts :: Foo a -> Bool
prop_inverse_stringsToInts (Foo st) = st == map show (stringsToInts st)
But now I am getting the error "* Ambiguous type variable a0' arising from a use of `quickCheck'" even though I am running quickCheck like this : > quickCheck (prop_inverse_stringsToInts :: Foo a -> Bool)
Can someone help please? Thank you in advance!
It seems you know the basics, but I'll repeat them here just to be sure. There are two ways to get QuickCheck to generate the inputs you want:
Have it generate some inputs and then filter out ones you don't want, or
Have it generate only the inputs you want.
You started with option 1, but as you saw, that didn't work out great. Compared to all possible lists of String, there really aren't that many that are digit lists. The better option is to generate only the inputs you want.
To succeed at option 2, you need to make a generator, which would be a value of type Gen [String] that generates lists of Strings that fit your criteria. The generator you propose still uses the method of filtering, so you may want to try a different approach. Consider instead, something like:
genDigitStrings :: Gen [String]
genDigitStrings = do
intList <- arbitrary :: Gen [Integer]
return $ fmap show intList
This generator produces arbitrary lists of Strings that are always shown integers, meaning that they will always be digit lists. You can then go ahead and insert this into an Arbitrary instance for some newtype if you want.
For your own sanity, you can even check your work with a test like this:
propReallyActuallyDigitStrings = forAll genDigitStrings isDigitList
If that passes, you have some confidence that your generator really only produces digit lists, and if it fails, then you should adjust your generator.

What are the Function types

The question is to determine function type of this : second xs = head (tail xs)
I tried everything
:t second gives me:
*Main> :type second
second :: [a] -> a --- is this the function type?
,then I tried :type second; :type "second xs = head (tail xs)".
It still does not work. How to determine Function type using Haskell
As you already know, you can use GHCi to find the type of a Haskell identifier by using the :type command (or its shorter version :t). In this case, GHCi gives you the answer second :: [a] -> a. The :: symbol means 'type-of', so this answer is just GHCi's way of telling you that 'the type of second is [a] -> a'.
But there's still another question here: what does this type mean? Well, let's pull it apart:
Any type of the form x -> y is the type of a function which takes as input one parameter of type x, and returns a value of type y.
In this case, we have a type [a] -> a, so the input type is [a] (i.e. a list of values of type a), and the output type is a (i.e. a single value of type a).
Thus, the statement second :: [a] -> a means that second is a function which takes as input a list of as, and gives as output a single value of the same type a. This ties in with what we know of the function: given a list, it returns a single value from that list.
EDIT: As #chepner pointed out in the comments, it is important to realise that a is a stand-in for any type. The only constraint is that, if the input is a list of as, then - no matter what a is - the return type must also be of type a. (This sort of indeterminate type is called a type variable.)

Haskell Programming Assignment, "Couldn't match expected type ‘Int’ with actual type ‘[a0] -> Int’ "and a few more Errors

The assignment I have: A function numOccurences that takes a value and a list, returning the number of times that value appears in the list. I am learning haskell and am getting frustrated, this is my code for this:
numOccurences:: b -> [a] -> Int
numOccurences n [ls]
|([ls] !! n==True) = (numOccurences(n (tail [ls])))+1
|otherwise = 0
The errors I am getting are as follows:
https://imgur.com/a/0lTBn
A few pointers:
First, in your type signature, using different type variables (i.e. b and a) creates the possibility that you could look for occurrences of a value of one type, in a list with another type, which in this case is not what you want. So instead of two type variables, you just want to use one.
Second, whatever the concrete type of your list is, whether it's [Char], [Int], etc., it needs to be equatable (i.e. it needs to derive the Eq typeclass), so it makes sense to use the class constraint (Eq a) => in your type signature.
Third, since we're traversing a list, let's use pattern matching to safely break off the first element of the list for comparison, and let's also add a base case (i.e. what we do with an empty list), since we're using recursion, and we only want the recursive pattern to match as long as there are elements in our list.
Lastly, try to avoid using indexing (i.e. !!), where you can avoid it, and use pattern matching instead, as it's safer and easier to reason about.
Here's how your modified function might look, based on the above pointers:
numOccurences :: (Eq a) => a -> [a] -> Int
numOccurences _ [] = 0
numOccurences n (x:xs)
| n == x = 1 + numOccurences n xs
| otherwise = numOccurences n xs

parse error on input ‘::’ when making an explicit type definition for a function which accepts multiple arguments

I am working on a project in Haskell for the first time and I am working on translating over my ADT into the code properly, however when I am writing the explicit type definitions for my functions and I load my code in GHCi I get the following error:
Blockquote parse error on input ‘::’
The line in question is for a function called type which accepts a character and a tuple and returns a tuple as shown below:
type :: validChars -> tuple -> tuple
where validChars is the list of valid characters, the definitions for my lists are shown here if this helps:
tuple = (l, r, b, k)
l = [l | l <- validChars]
m = [m | m <- validChars]
b = [b | b <- validChars]
k = [k | k <- validChars]
validChars = [ chr c | c <-alphanumericChars , c >= 32, c <= 122]
alphanumericChars = [ a | a <- [0..255]]
I checked to make sure it wasn't validChars causing the error by replacing it with the Charstype as shown:
type :: Chars -> tuple -> tuple
But I still get the same error, I am a complete beginner at Haskell so I'm probably missing something important, but I am not sure what that would be exactly; I've looked at answers for similar questions I have been unsuccessful thus far. Any help with this would be appreciated.
type is a keyword in Haskell, so you can't use it as the name of your function.
Furthermore type names start with a capital letter in Haskell and anything starting with a lower case letter in a type is a type variable. So if you define myFunction :: validChars -> tuple -> tuple, that defines a function that takes two arguments of arbitrary types and produces a result of the same type as the second argument. It's the same as myFunction :: a -> b -> b.
If you write myFunction :: Chars -> tuple -> tuple, you get a function whose first argument needs to be of type Chars (which needs to exist) and the second argument is of an arbitrary type that is also the type of the result. Again it's the same as myFunction :: Chars -> a -> a.
Note that for this to work, you'll actually have to have defined a type named Chars somewhere. If you want to take a list of Chars, the type should be [Char] instead.
And if you want the second argument and result to actually be tuples (rather than just a type variable arbitrarily named tuple), you need to specify a tuple type like (a,b,c,d), which would accept arbitrary 4-tuples, or something specific like (Integer, String, String, String), which would accept 4-tuples containing an Integer and three Strings.

Haskell ASCII codes

I'm trying to make a function that takes an a (which can be any type: int, char...) and creates a list which has that input replicated the number of times that corresponds to its ASCII code.
I've created this:
toList n = replicate (fromEnum n) n
When trying to use the function in the cmd it says it could match the expected type int with char, however if i use my function directly in the cmd with an actual value it does what it's supposed.
What i mean is: toList 'a' --> gives me an error
replicate (fromEnum 'a') 'a' --> gives a result without problem
I've loaded the module Data.Char (ord)
How can I fix this, and why does this happens?
Thanks in advance :)
What you're missing is a type declaration. You say that you want it to be able to take any type, but what you really want is toList to take something that is an instance of Enum. When you play around with it in GHCi, it'll let you do let toList n = replicate (fromEnum n) n, because GHCi will automatically pick some defaults that seem to make sense, but when compiling a module with GHC, it won't work without the type declaration. You want
toList :: (Enum a) => a -> [a]
toList n = replicate (fromEnum n) n
The reason why you have to have the (Enum a) => in the type signature is because fromEnum has the type signature (Enum a) => a -> Int. So you see it doesn't just take any type, only those that have an instance for Enum.

Resources