I'm studying for an exam about Haskell. I don't understand how I determine the type of a function. The function is:
func [] f = 16
func (h : t) f = (f h) + (func t f)
My guess is that the first line has this types: empty list -> a -> a where a has to be a numeric type. In Haskell notation Num a => [] -> a -> a and the second line has this types: [a]-> a -> ? What does it return? Maybe (a, a) because (f h) is a tuple. What about (func t f), is a or? And how do I mix both lines together?
func [] f = 16
This line defines a function func, accepting a list and f, and returning 16. The type could be written as Num a => [b] -> c -> a.
func (h : t) f = (f h) + (func t f)
This line restricts f type to Num a => b -> a, because:
f should accept an element from the list
f ... should return a value, which could be added to result of func ...
So, the type of func is:
Num a => [b] -> (b -> a) -> a
One (easy) way to find out about such problems is to write it in a file and load it into ghci and issue the command :t func, which is nice while preparing for an exam but not applicable during it - so I will walk you through the hints that can be found.
As #soon gave a perfectly valid answer - I will only add a few hints you might use in the future:
determine the number of arguments (this might be a bit difficult if the function is written in pointfree style, i.e. func x = const x could be written as func = const.
so in this case we get two arguments and one result so we can write the signature as
func :: ? -> ? -> ?
Look for results (in this case 16) and determine its type
you already noticed that 16 is something numerical - thus
func :: Num a => ? -> ? -> a
looks as a good starting point.
Look for type constructors that help you identify ADTs or type/newtypes in your function.
Now in the first and second case we have two hints that the first argument is of type list ([] and the constructor (:)) gives us this info. As we have no information about the contents of the list we have to assign a different type variable for them - b.
func :: Num a => [b] -> ? -> a
identify functions used to determine the rest or get more specialized types for the stuff you already found out
here we have 2 informations one is the (+) operator, and (f h) - as the whitespace character in haskell means function applicaton we get h's type has to be the domain of the function f and as the result of f h is used with (+) :: Num a => a -> a -> a (Note that both arguments must have the same type, as well as the result) and the result of func t f (which is a) we get the target type of f and therefore f :: b -> a
composing this we get
func :: Num a => [b] -> (type-of-f) -> a
func :: Num a => [b] -> (b -> a) -> a
Related
I am struggling with an exercise in R. Bird's functional programming book that asks for an example of a function with type (num -> num) -> num
The best I can come up with is a polymorphic type
func1 f = f 3
:t func1
func1 :: Num t1 => (t1 -> t2) -> t2
The problem I am having is that I can't specify the return type of f, so the type remains (num -> t2) -> t2.
My attempt to force the return type of f is as follows:
square x = x * x
:t func1 square
func1 square :: Num t2 => t2 -> t2
Because of course if I try to find the type of func1 ∘ square it will just be num -> num
If it is enough to give a function which can be assigned that type, then yours is already enough. That is, the following type-checks just fine:
func1 :: Num a => (a -> a) -> a
func1 f = f 3
If, on the other hand, you want a function which is inferred to have that type, then you need to do some trickery. What we want to do here is to specify that the result of f 3 and the 3 that we fed in have the same type. The standard way to force two terms to have the same type is to use asTypeOf, which is implemented this way:
asTypeOf :: a -> a -> a
asTypeOf x _ = x
So let's try:
> :t \f -> f 3 `asTypeOf` 3
(Num a, Num t) => (t -> a) -> a
Unfortunately for us, this doesn't work, because the 3 in f 3 and the standalone 3 are inferred to be using potentially different instances of Num. Still, it is a bit closer than \f -> f 3 was -- note the new Num a constraint on the output that we didn't have before. An obvious next idea is to let-bind a variable to 3 and reuse that variable as the argument to both f and asTypeOf; surely then GHC will get the picture that f's argument and result have the same type, right?
> :t \f -> let x = 3 in f x `asTypeOf` x
(Num a, Num t) => (t -> a) -> a
Drat. Turns out that lets do what's called "let generalization"; the x will be just as polymorphic as the 3 was, and can be specialized to different types at different use sites. Usually this is a nice feature, but because we're doing an unnatural exercise we need to do unnatural things...
Okay, next idea: some lambda calculi do not include a let, and when you need one, instead of writing let a = b in c, you write (\a -> c) b. This is especially interesting for us because Haskell uses a specially-restricted kind of polymorphism that means that inside c, the type of a is monomorphic. So:
> :t \f -> (\x -> f x `asTypeOf` x) 3
Num a => (a -> a) -> a
And now you complain that asTypeOf is cheating, because it uses a type declaration that doesn't match its inferred type, and the whole point of the exercise was to get the right type through inference alone. (If we were okay with using type declarations that don't match the inferred type, we could have stopped at func1 :: Num a => (a -> a) -> a; func1 f = f 3 from way back at the beginning!) Okay, no problem: there's another standardish way to force the types of two expressions to unify, namely, by putting them in a list together. So:
> :t \f -> (\x -> head [f x, x]) 3
Num a => (a -> a) -> a
Phew, now we're finally at a place where we could in principle build, from the ground up, all the tools needed to get a term of the right type without any type declarations.
func1 f = let x = f x in x This is a partial function, it technically has the type you want and you should be aware of what they are and how they work in haskell.
The question is:
Give a type declaration of (f True) (f 1) such that it is
well-typed or explain why it cannot exist.
Kindly please help me as I am unable to understand how to define type declaration. Thank you.
Here is how I would infer the type of f from your expression. Note that I'm not presenting how GHC works but how my "brain type checker" works.
f True is applied to a value, which means that the f on the left has type f True :: a -> b, so f :: Bool -> a -> b.
On the right, we have f 1, which means that on the right f :: (Num a) => a -> b, this is when my internal type checker starts to complain, because from the application of f on the left, I see that f can be applied to Bool, and on the right that it can be applied to a number, but Bool is not an instance of the Num class.
However this still type checks if there is no constraint on the first argument, so we have f :: a -> b and… we can't really say anything else I think. (Because b can be any type, it is perfectly possible that b is actually a c -> d, so we can obtain a new function from applying f partially.)
Note though that even if this type checks (you can check it in GHCi), it is very unlikely that f as a meaningful definition, in fact the only function it can represent that is not undefined is const I think (but correct if I'm wrong). You can say that because there is no constraint on the type of the first argument which is rather strange…
According to your comment f :: a -> b -> Bool (I was trying to have the most general type possible from the information given by the expression you typed, this is my result is a bit more general.)
There is only one way to define such a function without using undefined, it has to be a function that discards both its argument and give a constant. Because there is no way f can be defined for any type immaginable. So the definition of f is something like:
f _ _ = True
When you apply f True to f 1, you apply f True :: b -> Bool to a function f 1 :: b -> Bool, this is well typed because b is a type variable, it can be anything, in particular it is perfectly fine for b to be a c -> Bool, and in that case, the type of f True is in fact f True :: (c -> Bool) -> Bool. Is it clearer?
If you have the body of f, you can type ":t f" in GHCI (the haskell interpreter) to get its type.
If all you know about f is that (f True) (f 1) compiles, then f could be any constant function of 2 variables, like \x y -> 2 :: a -> b -> Int, or \x y = "foo" :: a -> b -> String or even \x y -> readFile "any.txt" :: a -> b -> IO (String).
I am trying to understand how this factorial example works using the function fix :: (a -> a) -> a.
Example:
factabs :: (Num a, Eq a) => (a -> a) -> a -> a
factabs fact 0 = 1
factabs fact x = x * fact (x-1)
f :: (Num a, Eq a) => a -> a
f = fix factabs
I do not see why fix factabs has this type... fix expects a function of type a -> a, how can we apply it to a function of type (a -> a) -> a -> a (a function that takes two parameters)? I am totally confused...
Basically I was trying to figure out how to convert the function limit below to something that uses fix. Would appreciate any help.
limit f n
| n == next = n
| otherwise = limit f next
where
next = f n
fix expects a function of type a -> a, how can we apply it to a function of type (a -> a) -> a -> a (a function that takes two parameters)? I am totally confused...
That works because all Haskell functions take just one parameter. Even though we often think of this type...
(a -> a) -> a -> a
... as one of a function of two arguments, we can also read it like...
(a -> a) -> (a -> a)
... that is, one of a function that takes one argument (an a -> a function) and produces a function of one argument (of type a). Now if we take...
fix :: (b -> b) -> b
... we can see how factabs fits it by replacing b with (a -> a).
Basically I was trying to figure out how to convert the function limit below to something that uses fix.
All you need to do is, starting from the original definition, replacing any recursive calls of limit with an extra argument and passing this limit-with-an-extra-argument to fix (as you will see, the types will match with no further ado).
Just for the record, here is a version of limit function that I posted in my question that uses fix:
limit :: Eq a => (a -> a) -> a -> a
limit = fix (\g f x -> let x' = f x
in if x == x' then x else g f x')
I have the applicative <$> operator more or less figured out, but I can't understand the signature I'm getting with the following example:
ghci> let f x y z = x + y + z -- f::Num a => a -> a -> a -> a
ghci> f <$> Just 2 <*> Just 3 <*> Just 4
Just 9
This result I understand, but when checking the following type:
ghci> :t (<$> f)
(<$> f) :: Num a => ((a -> a -> a) -> b) -> a -> b --This makes no sense to me
That signature I would understand as : a function that takes a (a -> a- > a) -> b function and an a as parameters and returns a b. According to this reasoning , I should call this like :
(<$>f) f 4
which would result in an Integer.
Obviously this is not true, so can you please help me understand how to read the type of (<$> f)?
a function that takes a (a -> a- > a) -> b function and an a as parameters and returns a b.
This is correct.
According to this reasoning , I should call this like :
(<$>f) f 4
which would result in an Integer.
No, because f does not have type (a -> a -> a) -> b or one compatible with it. Instead it has type Num a => a -> a -> a -> a. That is, f takes three numbers and produces a number, whereas we're looking for a function that takes a function (of type a -> a -> a) as its first argument.
<$> takes as a second argument something of type g b, where g is any applicative functor.
You are passing f :: Num a => a -> a -> a -> a as a second argument. Let's ignore the Num a context to keep things simple.
Hence, we look for g,b such that g b = a -> a -> a -> a.
Let's write the type of f in prefix form:
f :: (->) a ((->) a ((->) a a)) = g b
Hence, g = (->) a and b = ((->) a ((->) a a)). The latter is b = a -> a -> a in infix form.
It happens that (->) a is an applicative functor, so <$> f type checks. Note however that <$> is used on a completely different functor than the Maybe one you were using in your examples. Hence the confusion.
TL;DR: overloaded identifiers can shapeshift to many things adapting to their contexts, possibly in some unexpected way.
Having troubles with manually calculating types of given functions in Haskell for an exam at the weekend.
I understand the basics such as:
i x = x :: t -> t
k x y = x :: t -> t1 -> t
But having trouble on more complicated questions such as:
two f x = f (f x)
s x y z = x z (y z)
Any explanations would be much appreciated!
In those two examples the only hints you have as to the types of the functions come from observing the application going on. In Haskell application hardly has any syntax, so I'll rewrite them a bit more obviously.
two f x = f(f(x))
s x y z = x(z)(y(z))
We'll now discover the types of these functions through gradual refinement. For instance, beginning with two we know that it takes in two arguments and thus must have a type which agrees with the (more general) type
two :: a -> b -> c
We also know that the a type variable above actually corresponds to a function because f is being applied to both x and f(x).
two :: (a -> b) -> c -> d
Since f is applied to x we know that here a and c must be the same.
two :: (a -> b) -> a -> d
and since we apply f again to its result f(x) we know that the result type must be the same as the input type
two :: (a -> a) -> a -> b
And finally, the result of calling f is the total result of two so d must also equal a
two :: (a -> a) -> a -> a
This uses all of the information we have in the definition and is the most general type that is compatible with the definition of two.
We can do basically the same process for s. We know it has 3 arguments
s :: a -> b -> c -> d
We know that the first and second arguments are functions of some kind. We see the second argument applied to a single value and the first applied to two values.
s :: (a -> b -> c) -> (d -> e) -> f -> g
We also know that the first input to both functions are the same (namely, it's z each time). This lets us infer that a, d, and f are the same type
s :: (a -> b -> c) -> (a -> d) -> a -> e
We also know that the result of calling the second function is the second argument to the first function, so b and d must be the same.
s :: (a -> b -> c) -> (a -> b) -> a -> e
Finally, the result of fully applying the first function is the final result of s so c and e are the same
s :: (a -> b -> c) -> (a -> b) -> a -> c
While that might be a lot to digest and kind of a blur, the thing to emphasize is that the tools I've used to solve this problem are all primitive. Effectively, I introduce arrows (->) when I see that the type got applied to some values and thus must be a function of a certain number of arguments and I unify type variables by following the values through their expression. These are sufficient tools for inferring the types of simple functions like two and s.
Your two and s are what as known as higher level functions, because they take functions as arguments. You already have the tools to discern their types, you just have to be willing to be a bit more abstract about it.
If you're given the expression
f x
You know the type of f is a -> b with x :: a and f x :: b. If you see
f (f x)
Then you can deduce that the output type of (f x) is the same as the input type for f. This means that a ~ b, so f :: a -> a and x :: a. If we look at the type of two, we can deduce that it follows the pattern
two :: s -> t -> u
but the first argument to two is f, which has the type a -> a, so we can plug that in as
two :: (a -> a) -> t -> u
And x is the second argument with type a, so we can plug that in
two :: (a -> a) -> a -> u
And the return type is the same as the return type of f (f x), which has the return type of f, which has the return type of a, so if we plug that in we get the final type
two :: (a -> a) -> a -> a
For s, we can do similarly. We start off by saying s follows the form
s :: s -> t -> u -> v
since it has 3 arguments. The expression (y z) is function application, so y must have the type y :: a -> b, with z :: a. Plugging that in to s:
s :: s -> (a -> b) -> a -> v
Then we look at x z (y z). Since y z :: b and z :: a, x is a function of two arguments, the first of type a and the second of type b, with some unknown return type c, so we can plug that in as
s :: (a -> b -> c) -> (a -> b) -> a -> c
Let's look at
two f x = f (f x)
We will proceed by writing down what we know, using variables for anything we don't. Some of the things we know will be equations, and like in math, we will substitute around in the equations until we get something that we can't do anything else with.
Starting with the expression f x. f is a function, and its argument type is whatever x's type is, so:
x :: a -- a is a new variable
f :: a -> b -- b is a new variable
These two equations say exactly what I just said in the previous sentence. Also, we created the variable b which is the type of the result of the application:
f x :: b
Now let's move on to f (f x). So the argument type of f has to be the type of f x, which we know is b, so:
f :: b -> c -- c is a new variable
f (f x) :: c
But, of course, a function can only have one type, and we already have a type for f:
f :: a -> b -- from above
That means that
a = b
b = c
We've reached the top level expression now. So now let's look at the types of the input variables we've found together with the expression:
f :: a -> b
x :: a
f (f x) :: c
Now we go substituting around as much as we can, expressing it with as few variables as possible (but only using equalities that we have deduced). We'll try to do it all in terms of a.
f :: a -> b
= a -> a -- because b = a
x :: a
f (f x) :: c
= b -- because c = b
= a -- because b = a
And there we have it:
two :: (a -> a) -> a -> a
^^^^^^^^^ ^^^^^^^^^ ^^^^^^^^^^^^^^
type of f type of x type of result
This is more verbose than necessary, because I repeated myself a lot, so that you could see the reasoning involved. There is a methodical way to do this, but I prefer to do it more like math, going along and discovering what I can. The methodical way usually gets me lost in a sea of variables (which is easy enough for a computer, but hard for my mortal human brain).
I hope this helped.