Haskell type matching error - haskell

I have defined a couple of type synonyms as follows:
type Potential = Float
type Label = String
type LabelSet = [String]
In addition I have defined the following type and type synonym:
data VariableNode = VariableNode Label Potential LabelSet
type PGM = [VariableNode]
Finally, the following function to construct a graph:
makePGM :: [((Label, Potential), LabelSet)] -> PGM
makePGM (x:xs) = (VariableNode (fst . fst x) (snd . fst x) (snd x)) : makePGM xs
makePGM [] = []
In the above function, a list of tuples is provided where the first element of the tuple is another tuple and the second a list, as per the functions type signature.
I am new to Haskell so am having some difficulty in deciphering the following error messages:
Prelude> :l Graph.hs
[1 of 1] Compiling Graph ( Graph.hs, interpreted )
Graph.hs:14:33: error:
• Couldn't match type ‘a0 -> c0’ with ‘[Char]’
Expected type: Label
Actual type: a0 -> c0
• Probable cause: ‘(.)’ is applied to too few arguments
In the first argument of ‘VariableNode’, namely ‘(fst . fst x)’
In the first argument of ‘(:)’, namely
‘(VariableNode (fst . fst x) (snd . fst x) (snd x))’
In the expression:
(VariableNode (fst . fst x) (snd . fst x) (snd x)) : makePGM xs
Graph.hs:14:39: error:
• Couldn't match expected type ‘a0 -> (c0, b0)’
with actual type ‘(Label, Potential)’
• Possible cause: ‘fst’ is applied to too many arguments
In the second argument of ‘(.)’, namely ‘fst x’
In the first argument of ‘VariableNode’, namely ‘(fst . fst x)’
In the first argument of ‘(:)’, namely
‘(VariableNode (fst . fst x) (snd . fst x) (snd x))’
Graph.hs:14:47: error:
• Couldn't match type ‘a1 -> c1’ with ‘Float’
Expected type: Potential
Actual type: a1 -> c1
• Probable cause: ‘(.)’ is applied to too few arguments
In the second argument of ‘VariableNode’, namely ‘(snd . fst x)’
In the first argument of ‘(:)’, namely
‘(VariableNode (fst . fst x) (snd . fst x) (snd x))’
In the expression:
(VariableNode (fst . fst x) (snd . fst x) (snd x)) : makePGM xs
Graph.hs:14:53: error:
• Couldn't match expected type ‘a1 -> (a2, c1)’
with actual type ‘(Label, Potential)’
• Possible cause: ‘fst’ is applied to too many arguments
In the second argument of ‘(.)’, namely ‘fst x’
In the second argument of ‘VariableNode’, namely ‘(snd . fst x)’
In the first argument of ‘(:)’, namely
‘(VariableNode (fst . fst x) (snd . fst x) (snd x))’
Failed, modules loaded: none.
I have concluded that there are type mismatches but am not clear how so, given the types I have defined and the functions type signature.

The problem is that f . g x is f . (g x). Therefore, the types don't match:
fst . fst ((1,2),3)
== fst . (fst ((1,2),3))
== fst . (1,2)
== ???? (.) expects a function, not a value
You either have to use parentheses around fst . fst or $:
-- reminder:
(.) :: (b -> c) -> (a -> b) -> a -> c
(.) f g x = f (g x)
($) :: (a -> b) -> a -> b
($) f x = f x
(fst . fst) x
== fst (fst x)
fst $ fst x
== fst (fst x)
You can also combine both, e.g. fst . fst $ x, since the precedence of $ is low.

Of course, this is a useful exercise to do, and as a result of making this mistake you've learned to better understand operator precedence and parsing in Haskell. However, once you have more experience you'll realize you could have avoided the problem, and wound up with simpler code as a result, by using pattern matching instead of composing calls to fst and snd:
makePGM :: [((Label, Potential), LabelSet)] -> PGM
makePGM (((label, potential), set):xs) = VariableNode label potential set : makePGM xs
makePGM [] = []
Now the code is shaped like the data it consumes, and you get to give descriptive names to the values you work with.
Another improvement comes from observing that this recursive pattern is very common: you do something to each item in the list, independent of each other, and construct a list of the results. In fact, that is exactly what map does. So you could write a function that deals with only one of these PGM items at a time, and then use map to extend it to a function that works on a list of them:
makePGM :: [((Label, Potential), LabelSet)] -> PGM
makePGM = map go
where go ((label, potential), set) = VariableNode label potential set

Related

Refactoring Haskell lambda functions

I have a lambda function ((:) . ((:) x)) that I am passing to foldr like so: foldr ((:) . ((:) x)) [] xs where xs is a 2d list. I would like to refactor to make it clearer (so I can better understand it). I imagine it would be done like so:
foldr (\ element acc -> (element:acc) . (x:acc)) [] xs
But this gives me the error:
ex.hs:20:84: error:
• Couldn't match expected type ‘a0 -> b0’ with actual type ‘[[a]]’
• Possible cause: ‘(:)’ is applied to too many arguments
In the second argument of ‘(.)’, namely ‘(x : acc)’
In the expression: (element : acc) . (x : acc)
In the first argument of ‘foldr’, namely
‘(\ element acc -> (element : acc) . (x : acc))’
• Relevant bindings include
acc :: [[a]] (bound at ex.hs:20:60)
element :: [a] (bound at ex.hs:20:52)
xs :: [[a]] (bound at ex.hs:20:30)
x :: [a] (bound at ex.hs:20:28)
prefixes :: [a] -> [[a]] (bound at ex.hs:20:1)
|
20 | prefixes = foldr (\x xs -> [x] : (foldr (\ element acc -> (element:acc) . (x:acc)) [] xs)) []
|
Edit: My all relevant code surrounding this snippet is
prefixes :: Num a => [a] -> [[a]]
prefixes = foldr (\x acc -> [x] : (foldr ((:) . ((:) x)) [] acc)) []
and its invocation is:
prefixes [1, 2, 3]
How can I refactor the lambda ((:) . ((:) x)) to include both its arguments?
You can step-by-step convert it to a lambda.
(:) . ((:) x)
\y -> ((:) . (((:) x)) y -- conversion to lambda
\y -> (:) (((:) x) y) -- definition of (.)
\y -> (:) (x : y) -- rewrite second (:) using infix notation
\y z -> (:) (x : y) z -- add another parameter
\y z -> (x : y) : z -- rewrite first (:) using infix notation

Filtering on a List of Tuples

I'm trying to filter a list of 2-tuples where the first tuple value equals 0:
ghci> ys
[(0,55),(1,100)]
ghci> filter (\x -> x.fst == 0) ys
<interactive>:71:27:
Couldn't match type `(Integer, Integer)' with `b0 -> c0'
Expected type: [b0 -> c0]
Actual type: [(Integer, Integer)]
In the second argument of `filter', namely `ys'
In the expression: filter (\ x -> x . fst == 0) ys
In an equation for `it': it = filter (\ x -> x . fst == 0) ys
My desired output:
[(1,100)]
How can I achieve this? Also, what does the compile-time error mean?
(.) is function composition, you want filter (\x -> fst x == 0) ys.
Edit: you actually want filter (\x -> fst x /= 0) ys because filter provides a list of values that satisfy the predicate.
The compile time error is complaining because the compiler infers that x must be a function because you're composing it with fst, but ys is not a list of functions.

implementation of unzip function in haskell

I am trying to implement the unzip function, I did the following code but I get error.
myUnzip [] =()
myUnzip ((a,b):xs) = a:fst (myUnzip xs) b:snd (myUnzip xs)
I know that problem is in the right side of the second line but I do know how to improve it .
any hint please .
the error that I am getting is
ex1.hs:190:22:
Couldn't match expected type `()' with actual type `[a0]'
In the expression: a : fst (myUnzip xs) b : snd (myUnzip xs)
In an equation for `myUnzip':
myUnzip ((a, b) : xs) = a : fst (myUnzip xs) b : snd (myUnzip xs)
ex1.hs:190:29:
Couldn't match expected type `(t0 -> a0, b0)' with actual type `()'
In the return type of a call of `myUnzip'
In the first argument of `fst', namely `(myUnzip xs)'
In the first argument of `(:)', namely `fst (myUnzip xs) b'
ex1.hs:190:49:
Couldn't match expected type `(a1, [a0])' with actual type `()'
In the return type of a call of `myUnzip'
In the first argument of `snd', namely `(myUnzip xs)'
In the second argument of `(:)', namely `snd (myUnzip xs)'
You could do it inefficiently by traversing the list twice
myUnzip [] = ([], []) -- Defaults to a pair of empty lists, not null
myUnzip xs = (map fst xs, map snd xs)
But this isn't very ideal, since it's bound to be quite slow compared to only looping once. To get around this, we have to do it recursively
myUnzip [] = ([], [])
myUnzip ((a, b):xs) = (a : ???, b : ???)
where ??? = myUnzip xs
I'll let you fill in the blanks, but it should be straightforward from here, just look at the type signature of myUnzip and figure out what you can possible put in place of the question marks at where ??? = myUnzip xs
I thought it might be interesting to display two alternative solutions. In practice you wouldn't use these, but they might open your mind to some of the possibilities of Haskell.
First, there's the direct solution using a fold -
unzip' xs = foldr f x xs
where
f (a,b) (as,bs) = (a:as, b:bs)
x = ([], [])
This uses a combinator called foldr to iterate through the list. Instead, you just define the combining function f which tells you how to combine a single pair (a,b) with a pair of lists (as, bs), and you define the initial value x.
Secondly, remember that there is the nice-looking solution
unzip'' xs = (map fst xs, map snd xs)
which looks neat, but performs two iterations of the input list. It would be nice to be able to write something as straightforward as this, but which only iterates through the input list once.
We can nearly achieve this using the Foldl library. For an explanation of why it doesn't quite work, see the note at the end - perhaps someone with more knowledge/time can explain a fix.
First, import the library and define the identity fold. You may have to run cabal install foldl first in order to install the library.
import Control.Applicative
import Control.Foldl
ident = Fold (\as a -> a:as) [] reverse
You can then define folds that extract the first and second components of a list of pairs,
fsts = map fst <$> ident
snds = map snd <$> ident
And finally you can combine these two folds into a single fold that unzips the list
unzip' = (,) <$> fsts <*> snds
The reason that this doesn't quite work is that although you only traverse the list once to extract the pairs, they will be extracted in reverse order. This is what necessitates the additional call to reverse in the definition of ident, which results in an extra traversal of the list, to put it in the right order. I'd be interested to learn of a way to fix that up (I expect it's not possible with the current Foldl library, but might be possible with an analogous Foldr library that gives up streaming in order to preserve the order of inputs).
Note that neither of these work with infinite lists. The solution using Foldl will never be able to handle infinite lists, because you can't observe the value of a left fold until the list has terminated.
However, the version using a right fold should work - but at the moment it isn't lazy enough. In the definition
unzip' xs = foldr f x xs
where
f (a,b) (as,bs) = (a:as, b:bs) -- problem is in this line!
x = ([], [])
the pattern match requires that we open up the tuple in the second argument, which requires evaluating one more step of the fold, which requires opening up another tuple, which requires evaluating one more step of the fold, etc. However, if we use an irrefutable pattern match (which always succeeds, without having to examine the pattern) we get just the right amount of laziness -
unzip'' xs = foldr f x xs
where
f (a,b) ~(as,bs) = (a:as, b:bs)
x = ([], [])
so we can now do
>> let xs = repeat (1,2)
>> take 10 . fst . unzip' $ xs
^CInterrupted
<< take 10 . fst . unzip'' $ xs
[1,1,1,1,1,1,1,1,1,1]
Here's Chris Taylor's answer written using the (somewhat new) "folds" package:
import Data.Fold (R(R), run)
import Control.Applicative ((<$>), (<*>))
ident :: R a [a]
ident = R id (:) []
fsts :: R (a, b) [a]
fsts = map fst <$> ident
snds :: R (a, b) [b]
snds = map snd <$> ident
unzip' :: R (a, b) ([a], [b])
unzip' = (,) <$> fsts <*> snds
test :: ([Int], [Int])
test = run [(1,2), (3,4), (5,6)] unzip'
*Main> test
([1,3,5],[2,4,6])
Here is what I got working after above guidances
myUnzip' [] = ([],[])
myUnzip' ((a,b):xs) = (a:(fst rest), b:(snd rest))
where rest = myUnzip' xs
myunzip :: [(a,b)] -> ([a],[b])
myunzip xs = (firstValues xs , secondValues xs)
where
firstValues :: [(a,b)] -> [a]
firstValues [] = []
firstValues (x : xs) = fst x : firstValues xs
secondValues :: [(a,b)] -> [b]
secondValues [] = []
secondValues (x : xs) = snd x : secondValues xs

Haskell component-by-component addition

I am trying do to the component-by-component addition of a list of tuples with the use of higher functions. The result should be the (sum of the first component, sum on the second component).
sumPointwise :: Num a => [(a,a)] -> (a,a)
sumPointwise tl = (sumPw1, sumPw2) -- 42:1
where sumPw1 = foldr (\ x y -> (fst x) + (fst y)) 0 tl
sumPw2 = foldr (\ x y -> (snd x) + (snd y)) 0 tl
But I'm getting the following error:
Couldn't match type `a' with `(a, b0)'
`a' is a rigid type variable bound by
the type signature for sumPointwise :: Num a => [(a, a)] -> (a, a)
at .hs:42:1
In the first argument of `fst', namely `y'
In the second argument of `(+)', namely `(fst y)'
In the expression: (fst x) + (fst y)
It seems like the lambda function is wrong. But I don't get it.
Thanks for your help!
The second argument of foldr is aggregate value: foldr :: (a -> b -> b) -> b -> [a] -> b. So, your expressions should look like
sumPw1 = foldr (\ x s -> (fst x) + s) 0 tl
More succinct way of solving your task is
sumPointwise tl = let (xs, ys) = unzip tl in (sum xs, sum ys)

Equivalent functions producing different interpreter results

Background: I'm investigating anonymous recursion, and I'm taking on the challenge of implementing the prelude without using any named recursion just to help it all sit nicely in my mind. I'm not quite there yet, and along the way I've run into something unrelated but still interesting.
map1 = \f -> \x -> if (tail x) == []
then [f (head x)]
else f (head x) : (map1 f (tail x))
map2 f x = if (tail x) == []
then [f (head x)]
else f (head x) : (map2 f (tail x))
map3 f (x:xs) = if xs == [] then [f x] else f x : (map3 f xs)
map4 f (x:[]) = [f x]
map4 f (x:xs) = f x : map4 f xs
GHC complains about the first one, is fine with the second and the third and fourth ones are there just to show how they could be implemented differently.
*Main> map1 (*2) [1..10]
<interactive>:1:15:
No instance for (Num ())
arising from the literal `10'
Possible fix: add an instance declaration for (Num ())
In the expression: 10
In the second argument of `map1', namely `[1 .. 10]'
In the expression: map1 (* 2) [1 .. 10]
*Main> map2 (*2) [1..10]
[2,4,6,8,10,12,14,16,18,20]
*Main> map3 (*2) [1..10]
[2,4,6,8,10,12,14,16,18,20]
*Main> map4 (*2) [1..10]
[2,4,6,8,10,12,14,16,18,20]
If I add a type signature to map1 it's all good.
map1 :: Eq a => (a -> b) -> [a] -> [b]
The first two functions seem pretty much the same to me, so I suppose my question is simply "What's going on here?"
You were bitten by the monomorphism restriction. Anything that is written as foo = ... - meaning that there are no arguments to the definition, and no explicit type is given - has to have a non-generic type according to this restriction. The generic type in this case would, as you said, have had to be Eq a => (a -> b) -> [a] -> [b], but since the monomorphism restriction applies, both a and b are replaced by (), the simplest type that can be inferred for the available type variables.
But, if you use the unconstrained null instead of (== []),
Prelude> let map0 = \f -> \x -> if null (tail x) then [f (head x)] else f (head x) : map0 f (tail x)
Prelude> :t map0
map0 :: (a -> t) -> [a] -> [t]
Prelude> map (*2) [1 .. 10]
[2,4,6,8,10,12,14,16,18,20]
it works without arguments or a signature. Only constrained type variables are subject to the monomorphism restriction.
And if you put the definition of map1 into a file and try to compile it or load it into ghci,
Ambiguous type variable `a0' in the constraint:
(Eq a0) arising from a use of `=='
Possible cause: the monomorphism restriction applied to the following:
map1 :: forall t. (a0 -> t) -> [a0] -> [t] (bound at Maps.hs:3:1)
Probable fix: give these definition(s) an explicit type signature
or use -XNoMonomorphismRestriction
In the expression: (tail x) == []
In the expression:
if (tail x) == [] then
[f (head x)]
else
f (head x) : (map1 f (tail x))
In the expression:
\ x
-> if (tail x) == [] then
[f (head x)]
else
f (head x) : (map1 f (tail x))
ghci only complained in the way it did because it uses ExtendedDefaultRules, otherwise you would have gotten an understandable error message.

Resources