I'm doing a school assignment in OCaml and I had a question regarding the meaning of an expression.
When defining function if I, for example, wrote:
let iter : int * (int -> int) -> (int -> int)
= fun (n,f) ->
What does (int -> int) mean? I understand the function itself receives a pair as an argument, but I don't fully understand what the parentheses mean...
The parentheses are there to disambiguate between a function of type (int -> int) - meaning it takes in a parameter of type int and returns an int - and possibly just two regular ints taken as parameters of that function. Without the first pair of parentheses for example, your iter would expect an(int, int) tuple, and in case no other parameter is present, expect an int -> int -> int as return type.
Note that the second pair of parentheses is not strictly necessary, but it can be a good indicator that you are expecting a function in return. Without that pair of parentheses, the function can be read as expect a tuple of (int, int -> int) plus another int, returning an int for example.
An example of a function with the same signature as your iter could be:
let random_func: int * (int -> int) -> (int -> int) =
fun (n, f) -> f
Find TL;DR below.
In lambda calculus (please bear with me), which is what ML-languages are rooted from, the core idea is all about abstracting an application or mapping of function to an argument. Only one argument.
λx[x + 1]
The λ in the above reads abstracting function x + 1 into an application waiting for a value for x, guard it from changing, and apply (replace the x in the function with the value and calculate).
The above in Ocaml would be equivalent to:
fun x -> x + 1
which has the type int -> int, or input type int and output type int. Now, lambda only deals with one argument at a time. How does that work with functions with multiple arguments like x*x -2*x + c (a polynomial function x2 − 2·x + c)? It evaluates the argument one at a time just like before.
λc[λx[x*x - 2*x + c]]
Thus, the output of the previous application becomes the input of the next one, and so on. The Ocaml equivalent would be
fun c x -> (x * x) - (2 * x) + c
The function has type int -> int -> int or (int -> int) -> int (chain of input -> output) If you apply the function partially to an argument x = 3, you get a reduced function like so:
fun c 3 -> (3 * 3) - (2 * 3) + c
fun c -> 9 - 6 + c
fun c -> 3 + c
at which the resulting function would have the type of int -> int. This is the basis of currying. It might look confusing at first, but it proves to be very useful and under-appreciated in imperative languages. For instance, you could do something like this:
let waiting_for_c_and_x = fun c x -> 2*x + c
let waiting_for_c = waiting_for_c_and_x 10 in
let result = waiting_for_c 2 (* result = 22 *)
TL;DR
However, using parentheses to group these chains of inputs/outputs are tricky but necessary in Ocaml because in reality the compiler cannot guess from e.g. int * int -> int if you mean an application that accepts an int * int pair as an input and return an int as an output (which we could parenthesize as (int * int) -> int) or one that accepts a pair of int and a function of type int -> int as argument (which could be written as int * (int -> int)).
Applied from Stanford Encyclopedia of Philosophy (very good read)
Related
I am working on the following exercise:
Define a function libDiv which computes the list of natural divisors of some positive integer.
First define libDivInf, such that libDivInf n i is the list of divisors of n which are lesser than or equal to i
libDivInf : int -> int -> int list
For example:
(liDivInf 20 4) = [4;2;1]
(liDivInf 7 5) = [1]
(liDivInf 4 4) = [4;2;1]
Here's is my attempt:
let liDivInf : int -> int -> int list = function
(n,i) -> if i = 0 then [] (*ERROR LINE*)
else
if (n mod i) = 0 (* if n is dividable by i *)
then
i::liDivInf n(i-1)
else
liDivInf n(i-1);;
let liDiv : int -> int list = function
n -> liDivInf n n;;
I get:
ERROR: this pattern matches values of type 'a * 'b ,but a pattern
was expected which matches values of type int
What does this error mean? How can I fix it?
You've stated that the signature of liDivInf needs to be int -> int -> int list. This is a function which takes two curried arguments and returns a list, but then bound that to a function which accepts a single tuple with two ints. And then you've recursively called it in the curried fashion. This is leading to your type error.
The function keyword can only introduce a function which takes a single argument. It is primarily useful when you need to pattern-match on that single argument. The fun keyboard can have multiple arguments specified, but does not allow for pattern-matching the same way.
It is possible to write a function without using either.
let foo = function x -> x + 1
Can just be:
let foo x = x + 1
Similarly:
let foo = function x -> function y -> x + y
Can be written:
let foo x y = x + y
You've also defined a recursive function, but not included the rec keyword. It seems you're looking for something much more like the following slightly modified version of your attempt.
let rec liDivInf n i =
if i = 0 then
[]
else if (n mod i) = 0 then
i::liDivInf n (i-1)
else
liDivInf n (i-1)
I am trying to learn Haskell programming language by trying to figure out some pieces of code.
I have these 2 small functions but I have no idea how to test them on ghci.
What parameters should I use when calling these functions?
total :: (Integer -> Integer) -> Integer -> Integer
total function count = foldr(\x count -> function x + count) 0 [0..count]
The function above is supposed to for the given value n, return f 0 + f 1 + ... + f n.
However when calling the function I don't understand what to put in the f part. n is just an integer, but what is f supposed to be?
iter :: Int -> (a -> a) -> (a -> a)
iter n f
| n > 0 = f . iter (n-1) f
| otherwise = id
iter' :: Int -> (a -> a) -> (a -> a)
iter' n = foldr (.) id . replicate n
This function is supposed to compose the given function f :: a -> a with itself n :: Integer times, e.g., iter 2 f = f . f.
Once again when calling the function I don't understand what to put instead of f as a parameter.
To your first question, you use any value for f such that
f 0 + f 1 + ... + f n
indeed makes sense. You could use any numeric function capable of accepting an Integer argument and returning an Integer value, like (1 +), abs, signum, error "error", (\x -> x^3-x^2+5*x-2), etc.
"Makes sense" here means that the resulting expression has type ("typechecks", in a vernacular), not that it would run without causing an error.
To your second question, any function that returns the same type of value as its argument, like (1+), (2/) etc.
As the questions states, I am having a little trouble with defining a function with parameters different types. (array of Num, two parameters Int and returning Int).
This is function title:
_sum_divide :: (Num a) => [a] -> (Int b) => b -> b -> b
And I get this error I cannot figure out
`Int' is applied to too many type arguments
In the type signature for `_sum_divide':
_sum_divide :: Num a => [a] -> Int b => b -> b -> b
Sorry for the silly error, I am a noob with Haskell.
Thanks, have a good day/evening.
This seems to be a basic confusion between the concepts of type classes and of types. OO languages throw these all together, but in Haskell they are fundamentally different things.
A type is a set† of values. For example, the type Bool contains the values False and True. The type Int contains the values 0, 1 ... 9223372036854775807 and their negatives.
A type class is a set of types. For example, the class Num contains the type Int, the type Double, the type Rational... and whatever type T of your own, if you just define an instance Num T.
Generally, types are used in function signatures just by naming them. For instance,
foo :: [Int] -> [Int]
foo = map (*3)
is a function accepting a list of Int numbers (i.e. values of type Int), and gives another such list as the result (wherein each entry is tripled).
There is no constraint at all in the signature of foo. I could actually add one, like
foo :: Num Int => [Int] -> [Int]
This would express that the function needs Int to be an instance of the Num class to work. Well, it does need that in order to be able to calculate *3, but the constraint is superfluous, because we know that Int is a Num instance, the compiler doesn't just forget about that.
Where constraints are really useful is in polymorphic functions. For example, the following function triples every entry in a list of numbers, and doesn't care what particular type the numbers have:
foo :: Num n => [n] -> [n]
foo = map (*3)
This notation with type variables like a is actually shorthand for
foo :: ∀ n . Num n => [n] -> [n]
meaning, for all numerical types n, the function foo maps lists of n-values to lists of n-values.
It's important that constraints are completely separate‡ from the actual type specification in a signature. For instance, to specify for a polymorphic function [a] -> b -> b -> b that a should be a Num instance and b an Integral instance (the class of whole-number types, containing amongst other Int), you'd write
sum_divide :: (Num a, Integral b) => [a] -> b -> b -> b
Alternatively, if you really mean Int – that's just a single type, no reason to introduce a type variable for it.
sum_divide :: Num a => [a] -> Int -> Int -> Int
...although, you can still introduce the b variable if you like. You'll need an equational constraint (those are basically ad-hoc type classes containing only a single type)
{-# LANGUAGE TypeFamilies #-}
sum_divide :: (Num a, b ~ Int) => [a] -> b -> b -> b
†Mathematicians would object about several levels of differences between types, sets and classes. Read my notion of “set” as just “collection of things”.
‡In more complicated settings you can actually mix constraints and types, but that's advanced stuff.
The signature for a function that takes list of Nums and 2 int, and returns an int is:
_sum_divide :: (Num a) => [a] -> Int -> Int -> Int
The part before the thick arrow specifies the constraints. The part after it is where you use the constraints.
You had 2 main issues:
There should only 1 list of constraints in a signature.
Int isn't a Typeclass. (Num a) means a can be any type that supports the Num Typeclass. Int however is a concrete type, not a Typeclass, so (Int b) doesn't make sense.
I'm completely lost on this. It was explained that functions are right justified so that let add x y = x + y;; has a function type of int -> int -> int or int -> (int -> int).
I'm not sure how I'd define a function of type (int -> int) -> int. I was thinking I'd have the first argument be a function that passes in an int and returns an int. I've tried:
let add = fun x y -> x + y --- int -> int -> int
let add = fun f x = (f x) + 3 --- ('a -> int) -> 'a -> int
What about
let eval (f: int -> int) :int = f 0
?
fun x -> (x 1) + 1;;
- : (int -> int) -> int = <fun>
or
let foo f = (f 1) + 1;;
val foo : (int -> int) -> int = <fun>
it works like
foo (fun x -> x + 1);;
- : int = 3
Your questions is highly associated with the notion of Currying.
But before that, let me say that if you want to write a function that needs a parameter to be a function, you could declare a normal function, and just use its parameter like a function. No need to complicate it. See the ex:
let f x = x(10) + 10
Now comes the currying part. In OCaml, the parameters are semantically evaluated just one at a time, and after evaluating an argument, an anonymous function is returned. This is important because it lets you supply part of the arguments of a function, creating effectively a new function (which is called Partial Application).
In the example bellow, I use + as a function (parenthesis around an operator turn it to a normal function), to create an increment function. And apply it to the previous f function.
let incr = (+) 1
f incr
The code evaluates to f incr = incr(10) + 10 = 21
This link has more information on the topic applied to OCaml.
Im trying to understand Haskell and I have a question: What is the type of this function and how do you call it.
two f(a,b) = f a b
If we take, for example, arguments of type Int, then the type of two is like this:
two :: (Int -> Int -> Int) -> (Int, Int) -> Int
two f (a,b) = f a b
example:
two (*) (3,4)
12
Explanation:
You are taking a function that takes 2 arguments (Int -> Int -> Int)and a tuple (Int, Int) and applying that function to a and b.
The actual type, when not constrained, is actually like this:
:t two
two :: (t1 -> t2 -> t) -> (t1, t2) -> t
So for example other things are possible:
two (++) ("he","llo")
"hello"
(etc etc.)