Number of functions in expression - SML - function

How many functions are present in this expression? :
'a -> 'a -> ('a*'a)
Also, how would you implement a function to return this type? I've created functions that have for example:
'a -> 'b -> ('a * b)
I created this by doing:
fun function x y = (x,y);
But I've tried using two x inputs and I get an error trying to output the first type expression.
Thanks for the help!

To be able to have two inputs of the same alpha type, I have to specify the type of both inputs to alpha.
E.g
fun function (x:'a) (y:'a) = (x, y);
==>
a' -> 'a -> (a' * 'a)

Assuming this is homework, I don't want to say too much. -> in a type expression represents a function. 'a -> 'a -> ('a * 'a) has two arrows, so 2 might be the answer for your first question, though I find that particular question obscure. An argument could be made that each fun defines exactly one function, which might happen to return a function for its output. Also, you ask "how many functions are present in the expression ... " but then give a string which literally has 0 functions in it (type descriptions describe functions but don't contain functions), so maybe the answer is 0.
If you want a natural example of int -> int -> int * int, you could implement the functiondivmod where divmod x y returns a tuple consisting of the quotient and remainder upon dividing x by y. For example, you would want divmod 17 5 to return (3,2). This is a built-in function in Python but not in SML, but is easily defined in SML using the built-in operators div and mod. The resulting function would have a type of the form 'a -> 'a -> 'a*'a -- but for a specific type (namely int). You would have to do something which is a bit less natural (such as what you did in your answer to your question) to come up with a polymorphic example.

Related

Need a function that has type 'a * 'b -> 'b -> 'a

I'm new to OCAML, I'm trying this :
fun(a,b) b -> a;;
but I get this instead:
'a * 'b -> 'c -> 'a
How do I fix it?
First, your function has the strange property that the second parameter (named b) is going to shadow the second element of the first parameter (a tuple). In other words, in the body of your function the name b refers only to the second parameter and the second element of the tuple can't be accessed.
You would get the same type if you defined your function like this:
# fun (x, y) z -> x;;
- : 'a * 'b -> 'c -> 'a = <fun>
It's important to realize that the names of the parameters are completely unrelated to the names used for the type variables.
You can give your function the desired type if you make sure the second parameter is of the same type as the second element of the tuple. The purpose of the exercise is to get you to think about the type inference mechanism enough to think of a way to get this to happen. What operation could the function perform that can only be done on two values of the same type (but for any type)?

When can you call functions with labeled arguments without the labels?

It seems that in certain situations you can call functions with labeled arguments without the labels if they're in the right order; e.g.
let f ~x ~y = Format.sprintf "%d %s" x y;;
f 3 "test";;
runs successfully, but
f "test" 3;;
fails with the error message
Line 1, characters 2-8:
Error: This expression has type string but an expression was expected of type
int
For functions with optional arguments, it seems to work if you don't pass in the optional arguments:
let f ?(x = 1) ~y () = Format.sprintf "%d %s" x y;;
f "help" ();;
succeeds, but
f 2 "help" ();;
fails with the error message
Line 1, characters 4-10:
Error: The function applied to this argument has type
?x:int -> y:string -> string
This argument cannot be applied without label
Is there a general rule for when this is possible?
You can omit labels if the application is total (i.e., all required arguments are provided) and if the return type of the function is not a type variable. Arguments to the optional parameters must always be passed by a label.
Let's do some examples,
let example1 ?(opt=0) ~a ~b ~c unlabeled =
opt + a + b + c + unlabeled;;
example1 1 2 3 4;;
- : int = 10
Here we were able to apply all arguments without labels, because we have provided all required arguments (the optional parameter is not required, hence the name), and the resulting type is not polymorphic. However, if we will take the List.fold function from Core or ListLabels, which has type
'a list -> init:'accum -> f:('accum -> 'a -> 'accum) -> 'accum
Then we will get,
List.fold [1;2;3;4] 0 (+);;
- : init:(int -> (int -> int -> int) -> '_weak1) ->
f:((int -> (int -> int -> int) -> '_weak1) ->
int -> int -> (int -> int -> int) -> '_weak1) ->
'_weak1
instead of 10, which one would expect. The reason for that is since the resulting type 'accum is a type variable, so it could also be a function, e.g., int -> int or string -> int -> unit, etc -- all those types match with the 'accum type. That basically means that this function accepts a potentially infinite number of positional arguments. Therefore, all arguments that we provided were interpreted as positional, and as a result, we never were able to fill in the labeled arguments, therefore, our application wasn't made total. This actually makes our original definition of the rule at the beginning of the posting redundant - since an application, which type is denoted with a type variable, could never be total.
Note, that this problem only occurs when the return type is a type variable, not just includes some type variables, for example, we can easily omit labels with the List.map function, e.g, given List.map from Core, which has type
'a list -> f:('a -> 'b) -> 'b list
we can easily apply it
# List.map [1;2;3] ident;;
- : int Core_kernel.List.t = [1; 2; 3]
With all that being said, it is usually assumed a bad practice to omit the labels. Mainly because of the caveats with polymorphic return types and because it makes the order of the labeled arguments important, which is sort of counter-intuitive.
Yes, there is a general rule for this. From the manual:
Formal parameters and arguments are matched according to their respective labels, the absence of label being interpreted as the empty label. This allows commuting arguments in applications. One can also partially apply a function on any argument, creating a new function of the remaining parameters.
If several arguments of a function bear the same label (or no label), they will not commute among themselves, and order matters. But they can still commute with other arguments.
As an exception to the above parameter matching rules, if an application is total (omitting all optional arguments), labels may be omitted. In practice, many applications are total, so that labels can often be omitted.

PolyML Functions and Types

[...] a pair of functions tofun : int -> ('a -> 'a) and fromfun : ('a -> 'a) ->
int such that (fromfun o tofun) n evaluates to n for every n : int.
Anyone able to explain to me what this is actually asking for? I'm looking for more of an explanation of that than an actual solution to this.
What this is asking for is:
1) A higher-order function tofun which when given an integer returns a polymorphic function, one which has type 'a->'a, meaning that it can be applied to values of any type, returning a value of the same type. An example of such a function is:
- fun id x = x;
val id = fn : 'a -> 'a
for example, id "cat" = "cat" and id () = (). The later value is of type unit, which is a type with only 1 value. Note that there is only 1 total function from unit to unit (namely, id or something equivalent). This underscores the difficulty with coming up with defining tofun: it returns a function of type 'a -> 'a, and other than the identity function it is hard to think of other functions. On the other hand -- such functions can fail to terminate or can raise an error and still have type 'a -> 'a.
2) fromfun is supposed to take a function of type 'a ->'a and return an integer. So e.g. fromfun id might evaluate to 0 (or if you want to get tricky it might never terminate or it might raise an error)
3) These are supposed to be inverses of each other so that, e.g. fromfun (tofun 5) needs to evaluate to 5.
Intuitively, this should be impossible in a sufficiently pure functional language. If it is possible in SML, my guess is that it would be by using some of the impure features of SML (which allow for side effects) to violate referential transparency. Or, the trick might involve raising and handling errors (which is also an impure feature of SML). If you find an answer which works in SML it would be interesting to see if it could be translated to the annoyingly pure functional language Haskell. My guess is that it wouldn't translate.
You can devise the following property:
fun prop_inverse f g n = (f o g) n = n
And with definitions for tofun and fromfun,
fun tofun n = ...
fun fromfun f = ...
You can test that they uphold the property:
val prop_test_1 =
List.all
(fn i => prop_inverse fromfun tofun i handle _ => false)
[0, ~1, 1, valOf Int.maxInt, valOf Int.minInt]
And as John suggests, those functions must be impure. I'd also go with exceptions.

How to create matching pattern on a pair of functions in haskell [duplicate]

Imagine I have a custom type and two functions:
type MyType = Int -> Bool
f1 :: MyType -> Int
f3 :: MyType -> MyType -> MyType
I tried to pattern match as follows:
f1 (f3 a b i) = 1
But it failed with error: Parse error in pattern: f1. What is the proper way to do the above?? Basically, I want to know how many f3 is there (as a and b maybe f3 or some other functions).
You can't pattern match on a function. For (almost) any given function, there are an infinite number of ways to define the same function. And it turns out to be mathematically impossible for a computer to always be able to say whether a given definition expresses the same function as another definition. This also means that Haskell would be unable to reliably tell whether a function matches a pattern; so the language simply doesn't allow it.
A pattern must be either a single variable or a constructor applied to some other patterns. Remembering that constructor start with upper case letters and variables start with lower case letters, your pattern f3 a n i is invalid; the "head" of the pattern f3 is a variable, but it's also applied to a, n, and i. That's the error message you're getting.
Since functions don't have constructors, it follows that the only pattern that can match a function is a single variable; that matches all functions (of the right type to be passed to the pattern, anyway). That's how Haskell enforces the "no pattern matching against functions" rule. Basically, in a higher order function there's no way to tell anything at all about the function you've been given except to apply it to something and see what it does.
The function f1 has type MyType -> Int. This is equivalent to (Int -> Bool) -> Int. So it takes a single function argument of type Int -> Bool. I would expect an equation for f1 to look like:
f1 f = ...
You don't need to "check" whether it's an Int -> Bool function by pattern matching; the type guarantees that it will be.
You can't tell which one it is; but that's generally the whole point of taking a function as an argument (so that the caller can pick any function they like knowing that you'll use them all the same way).
I'm not sure what you mean by "I want to know how many f3 is there". f1 always receives a single function, and f3 is not a function of the right type to be passed to f1 at all (it's a MyType -> MyType -> MyType, not a MyType).
Once a function has been applied its syntactic form is lost. There is now way, should I provide you 2 + 3 to distinguish what you get from just 5. It could have arisen from 2 + 3, or 3 + 2, or the mere constant 5.
If you need to capture syntactic structure then you need to work with syntactic structure.
data Exp = I Int | Plus Exp Exp
justFive :: Exp
justFive = I 5
twoPlusThree :: Exp
twoPlusThree = I 2 `Plus` I 3
threePlusTwo :: Exp
threePlusTwo = I 2 `Plus` I 3
Here the data type Exp captures numeric expressions and we can pattern match upon them:
isTwoPlusThree :: Exp -> Bool
isTwoPlusThree (Plus (I 2) (I 3)) = True
isTwoPlusThree _ = False
But wait, why am I distinguishing between "constructors" which I can pattern match on and.... "other syntax" which I cannot?
Essentially, constructors are inert. The behavior of Plus x y is... to do nothing at all, to merely remain as a box with two slots called "Plus _ _" and plug the two slots with the values represented by x and y.
On the other hand, function application is the furthest thing from inert! When you apply an expression to a function that function (\x -> ...) replaces the xes within its body with the applied value. This dynamic reduction behavior means that there is no way to get a hold of "function applications". They vanish into thing air as soon as you look at them.

difficult to understand function definition

cube (x,y,z) =
filter (pcubes x) cubes
cubes = [(a,b,c) | a <- [1..30],b <- [1..30],c <- [1..30]]
pcubes x (b,n,m) = (floor(sqrt(b*n)) == x)
so this code works, cubes makes a list of tuples,pcubes is used with filter to filter all the cubes in which floor(sqrt(b*n)) == x is satisfied,but the person who has modified my code wrote pcubes x in filter (pcubes x) cubes,how does this work.pcubes x makes a function that will initial the cubes x (b,n,m) that will take in a tuple and output a bool.the bool will be used in the filter function. How does this sort of manipulation happen? how does pcubes x access the (b,n,m) part of the function?
In Haskell, we don't usually use tuples (ie: (a,b,c)) to pass arguments to functions. We use currying.
Here's an example:
add a b = a + b
Here add is a function that takes a number, the returns another function that takes a number, then returns a number. We represent it's type as so:
add :: Int -> (Int -> Int)
Because of the way -> behaves, we can remove the parentheses in this case:
add :: Int -> Int -> Int
It is called like this:
(add 1) 2
but because of the way application works, we can just write:
add 1 2
Doesn't that look like our definition above, of the form add a b...?
Your function pcubes is similar. Here's how I'd write it:
pcubes x (b,n,m) = floor (sqrt (b*n)) == x
And as someone else said, it's type could be represented as:
pcubes :: Float -> (Float, Float, Float) -> Bool
When we write pcubes 1 the type becomes:
pcubes 1 :: (Float, Float, Float) -> Bool
Which, through currying, is legal, and can quite happily be used elsewhere.
I know, this is crazy black functional magic, as it was for me, but before long I guarantee you'll never want to go back: curried functions are useful.
A note on tuples: Expressions like (a,b,c) are data . They are not purely function-argument expressions. The fact that we can pull it into a function is called pattern matching, though it's not my turn to go into that.