Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I get `Couldn't match expected type` in this Haskell code?

Tags:

haskell

I have a function that works fine:

      z::Int->Int->[Char]
      z x y =show(x)++show(y)++show(x*y)

It's really just a function that convert some numbers into a string. Then I quicksort the string with my quick sort function.

quicksort.z 2 3

but here I get the error

Couldn't match expected type `a0 -> [a1]' with actual type `[Char]'
In the return type of a call of `z'
In the second argument of `(.)', namely `z 2 3'
In the expression: flagskib . z 2 3

I tried fixes like parentheses and use of the $ function, but no help.

I appreciate any words on it. The problem is already fixed so the whole meaning of this post is to learn.

like image 826
Conformal Avatar asked Aug 30 '26 20:08

Conformal


2 Answers

quicksort takes one argument. z takes two. The composition operator has the following type

(.) :: (b -> c) -> (a -> b) -> a -> c

Perhaps you can see the problem now. The types do not match up.

quicksort $ z 2 3

Will work. So will quicksort . z 2 $ 3 or similarly (quicksort . z 2) 3 because the application of z to the argument 2 returns a function of one argument, which matches the type of (.) (partial application).

like image 101
Sarah Avatar answered Sep 03 '26 12:09

Sarah


I'm assuming quicksort has type[a] -> [a]. (.) is used for function composition, thus it expects two functions to compose but you use a [Char] instead. What you wrote is equivalent to \x -> quicksort ((z 2 3) x), which obviously doesn't work. You should use ($) instead, right-associative function application: quicksort $ z 2 3, equivalent to quicksort (z 2 3).

like image 34
Riccardo T. Avatar answered Sep 03 '26 13:09

Riccardo T.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!