Haskell: definition of counting function producing errors - haskell

So I defined a 'match' function as follows
let match :: Eq a => a -> [a] -> [Int]; match x = map (fromEnum . (==x))
Now I'm trying to define a new 'countN' function that counts the matches. When I try
let countN :: a -> [a] -> Int; countN x xs = ? $ match x xs
I get errors of the form: 'parse error of input '?''

You're getting an error because the compiler is parsing ? as an operator, and it sees two operators in a row, the second being $, which is illegal syntax. It looks like you copy/pasted this from somewhere that had the ? there as something to fill in, what do you think goes there?
EDIT:
To elaborate, what would you make of an expression like
myFunc x = + * ++ / x
To humans and any Haskell compiler, this expression makes no sense. What do all of those operators mean there? It can't be composition, the types wouldn't line up, and there just aren't enough arguments. This is the sort of problem the compiler has when it sees ? $ match x xs.

Related

Erroneous use of simple Haskell function

I'm learning Haskell and there's a lot of type-checking that seems completely nonsensical to me. I have written a simple function to count the number of occurrences of a given element in a given list, as such:
-- Count the number of occurrences of an element in a list.
countOcc :: (Eq a) => [a] -> a -> Int
countOcc xs x = length $ filter (== x) xs
Now, using this explicitly with calls such as:
countOcc "str" 's'
This executes fine, and returns correctly. However, this causes an error:
countOcc "str" "str"!!0
I haven't the foggiest why this should cause an error. "str"!!0 gives 's', a Char, which is exactly the same type passed in the second parameter of the first call.
I'm sure there are some nuances to Haskell's type system that I'm overlooking, or haven't broached yet. Ideally, I'd like to know why this is erroneous and furthermore, I'd like to know, according to Haskell's ideology, why it should be erroneous.
The following works fine:
countOcc :: (Eq a) => [a] -> a -> Int
countOcc xs x = length $ filter (== x) xs
main = print $ countOcc "str" ("str"!!0) -- 1
As far as I know, function applictaion has the highest precedence; although !! has precedence level of 9, it is still lower than function application.

Haskell: Parse error in pattern x ++ xs

Doing the third of the 99-Haskell problems (I am currently trying to learn the language) I tried to incorporate pattern matching as well as recursion into my function which now looks like this:
myElementAt :: [a] -> Int -> a
myElementAt (x ++ xs) i =
if length (x ++ xs) == i && length xs == 1 then xs!!0
else myElementAt x i
Which gives me Parse error in pattern: x ++ xs. The questions:
Why does this give me a parse error? Is it because Haskell is no idea where to cut my list (Which is my best guess)?
How could I reframe my function so that it works? The algorithmic idea is to check wether the list has the length as the specified inde; if yes return the last elemen; if not cut away one element at the end of the list and then do the recursion.
Note: I know that this is a really bad algorithm, but it I've set myself the challenge to write that function including recursion and pattern matching. I also tried not to use the !! operator, but that is fine for me since the only thing it really does (or should do if it compiled) is to convert a one-element list into that element.
Haskell has two different kinds of value-level entities: variables (this also includes functions, infix operators like ++ etc.) and constructors. Both can be used in expressions, but only constructors can also be used in patterns.
In either case, it's easy to tell whether you're dealing with a variable or constructor: a constructor always starts with an uppercase letter (e.g. Nothing, True or StateT) or, if it's an infix, with a colon (:, :+). Everything else is a variable. Fundamentally, the difference is that a constructor is always a unique, immediately matcheable value from a predefined collection (namely, the alternatives of a data definition), whereas a variable can just have any value, and often it's in principle not possible to uniquely distinguish different variables, in particular if they have a function type.
Yours is actually a good example for this: for the pattern match x ++ xs to make sense, there would have to be one unique way in which the input list could be written in the form x ++ xs. Well, but for, say [0,1,2,3], there are multiple different ways in which this can be done:
[] ++[0,1,2,3]
[0] ++ [1,2,3]
[0,1] ++ [2,3]
[0,1,2] ++ [3]
[0,1,2,3]++ []
Which one should the runtime choose?
Presumably, you're trying to match the head and tail part of a list. Let's step through it:
myElementAt (x:_) 0 = x
This means that if the head is x, the tail is something, and the index is 0, return the head. Note that your x ++ x is a concatenation of two lists, not the head and tail parts.
Then you can have
myElementAt(_:tl) i = myElementAt tl (i - 1)
which means that if the previous pattern was not matched, ignore the head, and take the i - 1 element of the tail.
In patterns, you can only use constructors like : and []. The append operator (++) is a non-constructor function.
So, try something like:
myElementAt :: [a] -> Int -> a
myElementAt (x:xs) i = ...
There are more issues in your code, but at least this fixes your first problem.
in standard Haskell pattern matches like this :
f :: Int -> Int
f (g n 1) = n
g :: Int -> Int -> Int
g a b = a+b
Are illegal because function calls aren't allowed in patterns, your case is just a special case as the operator ++ is just a function.
To pattern match on lists you can do it like this:
myElementAt :: [a] -> Int -> a
myElementAt (x:xs) i = // result
But in this case x is of type a not [a] , it is the head of the list and xs is its tail, you'll need to change your function implementation to accommodate this fact, also this function will fail with the empty list []. However that's the idiomatic haskell way to pattern match aginst lists.
I should mention that when I said "illegal" I meant in standard Haskell, there are GHC extensions that give something similar to that , it's called ViewPatterns But I don't think you need it especially that you're still learning.

Haskell code errors - I dont understand what it is asking for

First time poster, but this site has helped me alot.
I am trying to learn Haskell.
This is the question i'm asked to answer.
Write a function that takes a list (length >=2) of pairs of length and returns the first component of the second element in the list. So, when provided with [(5,’b’), (1,’c’), (6,’a’)], it will return 1.
I have done this myself.
listtwo :: [([a],b)] -> [a]
listtwo [] = []
listtwo [(a,b)] = fst (head (tail [(a,b)]))
I am trying to take a list of lists tuples I believe and return the 1st element from the 2nd item in the list. I know if you take out the [(a,b)]'s and replace the second [(a,b)] with a list like the one in the question it works fine. But when I try to make this function work for ANY list of tuples. I get errors.
Error I recieve
<interactive>:1:27:
No instance for (Num [a0])
arising from the literal `6'
Possible fix: add an instance declaration for (Num [a0])
In the expression: 6
In the expression: (6, 'a')
In the first argument of `listtwo', namely
`[(5, 'b'), (1, 'c'), (6, 'a')]'
So i'm asking if anyone can help me deciver the errors and mabye explain what I am doing wrong (don't give me the answer, cant learn that way).
Appriciate the help, might have more questions if this gets answered. Thank you very much in advance!
You say that you want a function that returns the first component of the second element of the list. The best way to write this function will be by pattern matching. But first, let's think about its type.
Say you want a list of tuples of (Int,Char). This is written as [(Int,Char)]. If you want a list of 2-tuples of arbitrary type, you replace the types Int and Char with type variables, so you end up with the type [(a,b)].
Your function needs to take something of this type, and return the first component of the second element of the list. All of the first components of the tuples have type a, so your return type must be a as well. So your function's type signature is
f :: [(a,b)] -> a
Now, how do we write this function? The best way is to use pattern matching. This is a neat way to extract the components of a data structure without having to use accessors (aka getters, if you come from an object-oriented background). Let's say we have a function g :: [a] -> a which returns the third component of a list. You could write
g :: [a] -> a
g xs = head (tail (tail xs))
but that looks pretty nasty. Another way is to pattern match. A list with three elements [x,y,z] can be constructed by doing x : y : z : [] where x, y and z are all of type a (remember that the operator : adds items to the front of a list). So we can write:
g :: [a] -> a
g (x : y : z : []) = z
But there's a problem with this - it only works on lists of length three, because our pattern says "Match a list of three elements with the empty list tacked on the end." Instead, we could use the pattern x : y : z : rest, where now rest matches the rest of the list:
g :: [a] -> a
g (x : y : z : rest) = z
where our pattern now says "Match a list of three elements followed by anything else at all." In fact, we can make it simpler. We aren't going to use the values x, y or rest so we can replace them with the Haskell pattern _ (underscore). This matches anything, and makes us promise that we aren't going to use that value:
g :: [a] -> a
g (_ : _ : z : _) = z
How can we use this to solve your problem? Well, if you had a list matching the pattern (w,x) : (y,z) : rest you would want to return y. So you can write:
f :: [(a,b)] -> a
f ( (w,x) : (y,z) : rest ) = y
which will work fine. However, you don't care about the first pair at all, so you can replace (w,x) with _. You also don't care about the second element of the second tuple or the rest of the list, so you can replace them with _ as well, getting:
f :: [(a,b)] -> a
f ( _ : (y,_) : _) = y
Checking it in ghci:
ghci> f [(5,'b'),(1,'c'),(6,'a')]
1
So it behaves as you expected it to.

Using Either correctly

So I have the following function:
chk2 :: [(Integer,Integer)] -> Either [(Integer,Integer)] (Integer,Integer)
chk2 i#((n,_):_)
| chkp (prod $ lgst i)==True = Right $ lgst i
| lgst i==i!!0 = Left $ chk2 $ (4-2,4-2):next i
| otherwise = Left $ chk2 $ next i
where prod (a,b) = a*b
lgst = foldl1 (\(a,b) (c,d) -> if prod (a,b) > prod (c,d) then (a,b) else (c,d))
next t = map (\(a,b) -> if (a,b)==lgst t then (a-1,b+1) else (a,b)) t
along with this error:
runhugs: Error occurred
ERROR "4/4.hs":14 - Type error in explicitly typed binding
*** Term : chk2
*** Type : [(Integer,Integer)] -> Either (Either [(Integer,Integer (Integer,Integer)) (Integer,Integer)
*** Does not match : [(Integer,Integer)] -> Either [(Integer,Integer)] (Integer,Integer)
I'm trying to get this function to either end up with an (a,b) i.e. first guard or [(a,b)] i.e. the latter two guards. The basic problem is in the latter two guards.. if I take out the recursion, everything works fine, but I'm not sure how to define the type signature when returning the function itself.
The problem is with how you recurse.
According to the type of chk2, chk2 $ next i is of type Either [(Integer,Integer)] (Integer,Integer). Left is of type b -> Either b a, so Left $ chk2 $ next i is of type Either (Either [(Integer,Integer)] (Integer,Integer)) a for some unspecified type a.
Left $ chk2 $ (4-2,4-2):next i has a similar problem.
To fix, you need to decide how you want to handle the recursive value.
Easy fix:
| lgst i==i!!0 = chk2 $ (4-2,4-2):next i
| otherwise = chk2 $ next i
However, I doubt this is what you want, since it means all your results will be Right.
I'm not sure how to do what you want, because I'm not sure what you want.
What does a list result mean? What does a non-list result mean?
What you probably want to do is pattern match the result of the recursion, transforming Right pair -> Left [pair], perhaps appending some other result to the front.
As an example, I'll construct a recursive function with a similar type signature. Let foo be a function that takes a list of integers, and:
if the first element of the list is the maximum of the whole list, returns that element
otherwise, return a subsequence of the list, where each is the maximum of all the elements between it and the next element in the subsequence (or the end)
To do this:
foo :: [Integer] -> Either [Integer] Integer
foo [] = Left []
foo (x:xs) = case foo xs of
Left ys -> if all (<=x) ys
then Right x
else let (_,ys') = break (>x) ys in Left (x:ys')
Right y -> if x >= y
then Right x
else Left [x,y]
Note how I use case to pattern match on the result of the recursive call to foo.
To solve Euler #4, yours seems to be a very awkward style for Haskell. It's usually a bad idea to try and "port" code from other languages into Haskell, since the paradigm for Haskell is so very different.
You'll find a very clean, sensible solution to Euler #4 that uses list comprehensions at the Haskell Wiki. Certainly not the only solution, but it is at least 20x as readable as your current code. No offense.
I (and tons of other Haskellers) highly recommend Learn You a Haskell and Real World Haskell for learning how to approach problems the Haskell way, which in my experience is usually to create small, simple helper methods and compose them into a solution.

When destructuring tuples in Haskell, where can the elements be used?

I am reading a tutorial that uses the following example (that I'll generalize somewhat):
f :: Foo -> (Int, Foo)
...
fList :: Foo -> [Int]
fList foo = x : fList bar
where
(x, bar) = f foo
My question lies in the fact that it seems you can refer to x and bar, by name, outside of the tuple where they are obtained. This would seem to act like destructuring parameter lists in other languages, if my guess is correct. (In other words, I didn't have to do the following:)
fList foo = (fst tuple) : fList (snd tuple)
where
tuple = f foo
Am I right about this behavior? I've never seen it mentioned yet in the tutorials/books I've been reading. Can someone point me to more info on the subject?
Edit: Can anything (lists, arrays, etc.) be destructured in a similar way, or can you only do this with tuples?
Seeing your edit, I think what your asking about is Pattern matching.
And to answer your question: Yes, anything you can construct, you can also 'deconstruct' using the constructors. For example, you're probably familiar with this form of pattern matching:
head :: [a] -> a
head (x:xs) = x
head [] = error "Can't take head of empty list"
However, there are more places where you can use pattern matching, other valid notations are:
head xs = case xs of
(y:ys) -> y
[] -> error "Can't take head of empty list"
head xs = let (y:ys) = xs
in y
head xs = y
where
(y:ys) = xs
Note that the last two examples are a bit different from the first to because they give different error messages when you call them with an empty list.
Although these examples are specific to lists, you can do the same with other data types, like so:
first :: (a, b) -> a
first tuple = x
where
(x, y) = tuple
second :: (a, b) -> b
second tuple = let (x, y) = tuple
in y
fromJust :: Maybe a -> a
fromJust ma = x
where
(Just x) = ma
Again, the last function will also crash if you call it with Nothing.
To sum up; if you can create something using constructors (like (:) and [] for lists, or (,) for tuples, or Nothing and Just for Maybe), you can use those same constructors to do pattern matching in a variety of ways.
Am I right about this behavior?
Yes. The names exist only in the block where you have defined them, though. In your case, this means the logical unit that your where clause is applied to, i.e. the expression inside fList.
Another way to look at it is that code like this
x where x = 3
is roughly equivalent to
let x = 3 in x
Yes, you're right. Names bound in a where clause are visible to the full declaration preceding the where clause. In your case those names are f and bar.
(One of the hard things about learning Haskell is that it is not just permitted but common to use variables in the source code in locations that precede the locations where those variables are defined.)
The place to read more about where clauses is in the Haskell 98 Report or in one of the many fine tutorials to be found at haskell.org.

Resources