Higher order function on lists Ocaml - functional-programming

I created a function p that checks if the square of a given value is lower than 30.
Then this function is called in an other function (as argument) to return the first value inside a list with its square less then 30 ( if p is true, basically I have to check if the function p is true or false ).
This is the code :
let p numb =
let return = (numb * numb) < 30 in return
let find p listT =
let rec support p listT =
match listT with
| []-> raise (Failure "No element in list for p")
| hd :: tl -> if p hd then hd
else support p tl in
let ret = support (p listT) in ret
let () =
let a = [5;6;7] in
let b = find p a in print_int b
But it said on the last line :
Error: This expression (p) has type int -> bool
but an expression was expected of type int -> 'a -> bool
Type bool is not compatible with type 'a -> bool
However, I don't think I'm using higher order functions in the right way, I think it should be more automatic I guess, or not?

First, note that
let return = x in return
can replaced by
x
Second, your original error is on line 10
support (p listT)
This line makes the typechecker deduce that the p argument of find is a function that takes one argument (here listT) and return another function of type int -> bool.

Here's another way to look at your problem, which is as #octachron says.
If you assume that p is a function of type int -> bool, then this recursive call:
support (p listT)
is passing a boolean as the first parameter of support. That doesn't make a lot of sense since the first parameter of support is supposed to be a function.
Another problem with this same expression is that it requires that listT be a value of type int (since this is what p expects as a parameter). But listT is a list of ints, not an int.
A third problem with this expression is that it only passes one parameter to support. But support is expecting two parameters.
Luckily the fix for all these problems is exremely simple.

Related

How to find the minimum element in a Map and return a tuple (key,minimum element)?

I have these types :
type position = float * float
type node = position
I've written those modules to create my Map :
module MyMap =
struct
type t = node
let compare (a1,b1) (a2,b2) =
if a1 > a2 then 1
else if a1 < a2 then -1
else if b1 > b2 then 1
else if b1 < b2 then -1
else 0
end
module DistMap = Map.Make(MyMap)
I've tried to write functions that used iter but my attempts to formulate my ideas in a correct syntax were unsuccessful.
My goal would be able to have a function that takes a Map as argument and return a tuple of the minimum element and its key.
Thanks.
If you're asking for the minimum key and its corresponding element, that's easy: use DistMap.min_binding_opt, or DistMap.min_binding if you're fine with raising an exception on an empty map.
If you're asking for the minimum element and its corresponding key, you will want to use a fold. Luckily, the DistMap module returned by Map.Make exposes a fold function, so you don't have to do extra allocation by, say, calling to_seq and doing a fold on the result. In addition, because the type of elements in a map is not constrained by the functor application (i.e., you can create a map with any element type), you will need the client to supply a comparison function for the element type.
DistMap.fold has type (key -> 'a -> 'b -> 'b) -> 'a t -> 'b -> 'b, so we'll have to instantiate 'b in such a way as to keep track of both the key and the min element; in other words, we'll instantiate 'a as the element type of the map (let’s call it t), and 'b as (key * t) option (where key = position = float * float).
Here's what the code might look like:
let min_element_and_its_key map ~compare_element =
let take_min key element key_and_min_element =
match key_and_min_element with
| None -> Some (key, element)
| Some (key_for_min_element, min_element) ->
if compare_element element min_element < 0
then Some (key, element)
else Some (key_for_min_element, min_element)
in
DistMap.fold take_min map None
min_element_and_its_key will return None on an empty map.
Example client code (which you can run in an ocaml repl) might look like:
let map = DistMap.(empty |> add (3., 3.) "a" |> add (4., 4.) "b") in
min_element_and_its_key map ~compare_element:String.compare;;
(* Output: *)
- : (node * string) option = Some ((3., 3.), "a")
In general, anytime that you want to traverse all keys/elements in a data structure and accumulate a value, a fold is the way to go. iter will sort of work, but you'll have to accumulate the value in mutable state instead of accumulating it directly as the return value of the function you're folding with.

Automatic detection of domain for dependent type function in Idris

Idris language tutorial has simple and understandable example of the idea of Dependent Types:
http://docs.idris-lang.org/en/latest/tutorial/typesfuns.html#first-class-types
Here is the code:
isSingleton : Bool -> Type
isSingleton True = Int
isSingleton False = List Int
mkSingle : (x : Bool) -> isSingleton x
mkSingle True = 0
mkSingle False = []
sum : (single : Bool) -> isSingleton single -> Int
sum True x = x
sum False [] = 0
sum False (x :: xs) = x + sum False xs
I decided to spend more time on this example. What bothers me in sum function is that I need to explicitly pass single : Bool value to function. I don't want to do this and I want compiler to guess what this boolean value should be. Hence I pass only Int or List Int to sum function there should be 1-to-1 correspondence between boolean value and type of argument (if I pass some other type this just mustn't type check).
Of course, I understand, this is not possible in general case. Such compiler tricks require my function isSingleton (or any other similar function) be injective. But for this case it should be possible as it seems to me...
So I started with next implementation: I just made single argument implicit.
sum : {single : Bool} -> isSingleton single -> Int
sum {single = True} x = x
sum {single = False} [] = 0
sum {single = False} (x :: xs) = x + sum' {single = False} xs
Well, it doesn't really solve my problem because I still need to call this function in the next way:
sum {single=True} 1
But I read in tutorial about auto keyword. Though I don't quite understand what auto does (because I didn't find description of it) I decided to patch my function just a little bit more:
sum' : {auto single : Bool} -> isSingleton single -> Int
sum' {single = True} x = x
sum' {single = False} [] = 0
sum' {single = False} (x :: xs) = x + sum' {single = False} xs
And it works for lists!
*DepFun> :t sum'
sum' : {auto single : Bool} -> isSingleton single -> Int
*DepFun> sum' [1,2,3]
6 : Int
But doesn't work for single value :(
*DepFun> sum' 3
When checking an application of function Main.sum':
List Int is not a numeric type
Can someone explain is it actually possible to achieve my goal in such injective function usages currently? I watched this short video about proving something is injective:
https://www.youtube.com/watch?v=7Ml8u7DFgAk
But I don't understand how I can use such proofs in my example.
If this is not possible what is the best way to write such functions?
The auto keyword basically tells Idris, "Find me any value of this type". So you're liable to get the wrong answer unless that type only contains one value. Idris sees {auto x : Bool} and fills it in with any old Bool, namely False. It doesn't use its knowledge of later arguments to help it choose - information doesn't flow from right to left.
One fix would be to make the information flow in the other direction. Rather using a universe-style construction as you have above, write a function accepting an arbitrary type and use a predicate to refine it to the two options you want. This way Idris can look at the type of the preceding argument and pick the only value of IsListOrInt whose type matches.
data IsListOrInt a where
IsInt : IsListOrInt Int
IsList : IsListOrInt (List Int)
sum : a -> {auto isListOrInt : IsListOrInt a} -> Int
sum x {IsInt} = x
sum [] {IsList} = 0
sum (x :: xs) {IsList} = x + sum xs
Now, in this case the search space is small enough (two values - True and False) that Idris could feasibly explore every option in a brute-force fashion and pick the first one that results in a program which passes the type checker, but that algorithm doesn't scale well when the types are much bigger than two, or when trying to infer multiple values.
Compare the left-to-right nature of the information flow in the above example with the behaviour of regular non-auto braces, which instruct Idris to find the result in a bidirectional fashion using unification. As you note, this could only succeed when the type functions in question are injective. You could structure your input as a separate, indexed datatype, and allow Idris to look at the constructor to find b using unification.
data OneOrMany isOne where
One : Int -> OneOrMany True
Many : List Int -> OneOrMany False
sum : {b : Bool} -> OneOrMany b -> Int
sum (One x) = x
sum (Many []) = 0
sum (Many (x :: xs)) = x + sum (Many xs)
test = sum (One 3) + sum (Many [29, 43])
Predicting when the machine will or won't be able to guess what you mean is an important skill in dependently-typed programming; you'll find yourself getting better at it with more experience.
Of course, in this case it's all moot because lists already have one-or-many semantics. Write your function over plain old lists; then if you need to apply it to a single value you can just wrap it in a singleton list.

Partition a list into equivalence classes

I am trying to write a function in SML which when given a list of general elements, reorders its elements into equivalent classes and returns a list of these classes (type "a list list).
Leave the elements in the classes in the same order as in the original list.
A given function defines the equivalence of the elements and it returns true if the elements are equivalent or false otherwise.
I cannot seem to get a grip on the solution.
fun sample x y = x = y
Required type: fn : (''a -> ''a -> bool) -> ''a list -> ''a list list
Thank you very much for the help.
The helper function does not work correctly, all I want to do with it is see if a given element belongs to any of the classes and put it accordingly inside or create a new sublist which contains it.
fun srt listoflists func new =
case listoflists of [] => [[]]
| a::b => if func (new, hd a) = true then (new::a)::b
else if func (new, hd a) = false then a::(srt b func new) else [new]::a::b
The sample functions checks equivalence of two elements when divided by 11.
Tests are not all working, it is not adding 17 into a new class.
srt [[7,7,7],[5,5,5],[11,11,11],[13,13,13]] eq 7;
val it = [[7,7,7,7],[5,5,5],[11,11,11],[13,13,13]] : int list list
- srt [[7,7,7],[5,5,5],[11,11,11],[13,13,13]] eq 5;
val it = [[7,7,7],[5,5,5,5],[11,11,11],[13,13,13]] : int list list
- srt [[7,7,7],[5,5,5],[11,11,11],[13,13,13]] eq 11;
val it = [[7,7,7],[5,5,5],[11,11,11,11],[13,13,13]] : int list list
- srt [[7,7,7],[5,5,5],[11,11,11],[13,13,13]] eq 13;
val it = [[7,7,7],[5,5,5],[11,11,11],[13,13,13,13]] : int list list
- srt [[7,7,7],[5,5,5],[11,11,11],[13,13,13]] eq 17;
val it = [[7,7,7],[5,5,5],[11,11,11],[13,13,13],[]] : int list list
- srt [[7,7,7],[5,5,5],[11,11,11],[13,13,13],[111,111,111]] eq 111;
val it = [[7,7,7],[5,5,5],[11,11,11],[13,13,13],[111,111,111,111]]
How to correct this and also once this helper function works, how to encorporate it exactly into the main function that is required.
Thank you very much.
Your example code seems like you are getting close, but has several issues
1) The basis cases is where new should be added, so in that case you should return the value [[new]] rather than [[]]
2) Your problem description suggests that func be of type ''a -> ''a -> bool but your code for srt seems to be assuming it is of type (''a * ''a) -> bool. Rather than subexpressions like func (new, hd a) you need func new (hd a) (note the parentheses location).
3) if func returns a bool then comparing the output to true is needlessly verbose, instead of if func new (hd a) = true then ... simply have if func new (hd a) then ...
4) Since you are adding [new] in the basis cases, your second clause is needlessly verbose. I see no reason to have any nested if expressions.
Since this seems to be homework, I don't want to say much more. Once you get the helper working correctly it should be fairly straightforward to use it (in the recursive case) of the overall function. Note that you could use (a # [new])::b rather than (new::a)::b if you want to avoid the need for a final mapping of rev across the final return value. # is more expensive than :: (it is O(n) rather than O(1)), but for small examples it really doesn't matter and could even be slightly better since it would avoid the final step of reversing the lists.

Int list to unit type

I am looking for a function for : int * int * (int -> unit) -> unit. I need this to print a list of numbers. To be more specific, I have a function f num = print ((Int.toString num)^"\n"). So far, I have this:
fun for(from,to,f)=
if from=to then [f(to)]
else f(from)::for(from+1,to,f)
which gives me a return type of unit list. How can I call for function without appending to earlier result?
The () you want to return is the () from the last call to f - that is, the call from the then branch.
Generally speaking, whenever you want to do two things, and only return the result of the second thing, you use the following syntax:
(thing1;thing2)
For example:
(print "foo\n"; 2 + 3);
Would print out the string "foo\n", and then return 5.
So now, let's look at the two branches of your code.
fun for (from,to,f) = if from = to
then ...
else ...
In the then branch, we simply call f on to. f already returns (), so we don't do anything more with the result:
fun for (from,to,f) = if from = to
then f to
else ...
The else branch is slightly more complicated. We want to call f on from, and then make a recursive call. The return type of the recursive call is unit, so that's what we want to return:
fun for (from,to,f) = if from = to
then f to
else (f from;for (from+1,to,f));
Another thing: What happens if you do this?
for (4,3,f)

Ocaml continuation passing style

I'm new to ocaml and tryin to write a continuation passing style function but quite confused what value i need to pass into additional argument on k
for example, I can write a recursive function that returns true if all elements of the list is even, otherwise false.
so its like
let rec even list = ....
on CPS, i know i need to add one argument to pass function
so like
let rec evenk list k = ....
but I have no clue how to deal with this k and how does this exactly work
for example for this even function, environment looks like
val evenk : int list -> (bool -> ’a) -> ’a = <fun>
evenk [4; 2; 12; 5; 6] (fun x -> x) (* output should give false *)
The continuation k is a function that takes the result from evenk and performs "the rest of the computation" and produces the "answer". What type the answer has and what you mean by "the rest of the computation" depends on what you are using CPS for. CPS is generally not an end in itself but is done with some purpose in mind. For example, in CPS form it is very easy to implement control operators or to optimize tail calls. Without knowing what you are trying to accomplish, it's hard to answer your question.
For what it is worth, if you are simply trying to convert from direct style to continuation-passing style, and all you care about is the value of the answer, passing the identity function as the continuation is about right.
A good next step would be to implement evenk using CPS. I'll do a simpler example.
If I have the direct-style function
let muladd x i n = x + i * n
and if I assume CPS primitives mulk and addk, I can write
let muladdk x i n k =
let k' product = addk x product k in
mulk i n k'
And you'll see that the mulptiplication is done first, then it "continues" with k', which does the add, and finally that continues with k, which returns to the caller. The key idea is that within the body of muladdk I allocated a fresh continuation k' which stands for an intermediate point in the multiply-add function. To make your evenk work you will have to allocate at least one such continuation.
I hope this helps.
Whenever I've played with CPS, the thing passed to the continuation is just the thing you would normally return to the caller. In this simple case, a nice "intuition lubricant" is to name the continuation "return".
let rec even list return =
if List.length list = 0
then return true
else if List.hd list mod 2 = 1
then return false
else even (List.tl list) return;;
let id = fun x -> x;;
Example usage: "even [2; 4; 6; 8] id;;".
Since you have the invocation of evenk correct (with the identity function - effectively converting the continuation-passing-style back to normal style), I assume that the difficulty is in defining evenk.
k is the continuation function representing the rest of the computation and producing a final value, as Norman said. So, what you need to do is compute the result of v of even and pass that result to k, returning k v rather than just v.
You want to give as input the result of your function as if it were not written with continuation passing style.
Here is your function which tests whether a list has only even integers:
(* val even_list : int list -> bool *)
let even_list input = List.for_all (fun x -> x mod 2=0) input
Now let's write it with a continuation cont:
(* val evenk : int list -> (bool -> 'a) -> 'a *)
let evenk input cont =
let result = even_list input in
(cont result)
You compute the result your function, and pass resultto the continuation ...

Resources