Extract two elements of list and pass the rest recursively - recursion

I have a type def with 2 types and a list of the same type that may or may not be empty.
type Type1 = string
type Type2 = int
type Type3 = Sometype of Type1 * Type2 * Type3 list
I am trying to create a list of all the first two elements in the tuple, recursively passing along the last (a list of other type 3's), appending it to the list that I'm producing. Or at least that's what I'm trying. My function gives me an error:
let rec extSometypeInc d =
match d with
| Sometype(n,i,[]) -> [(n,i)]
| Sometype(n,i,r1::r2::rt) -> (n,i) :: extSometypeInc(r1,r2,rt)
;;
error FS0001: This expression was expected to have type
Type3
but here has type
'a * 'b * 'c

I'm not fully sure of your end goal here, but in terms of the unexpected result type you seem to have a syntax error.
| Sometype(n,i,r1::r2::rt) -> (n,i) :: extSometypeInc(r1,r2,rt)
Will pass a single tuple of three values to extSometypeInc as its first argument.
I believe you want:
| Sometype(n,i,r1::r2::rt) -> (n,i) :: (extSometypeInc r1 r2 rt)
which will pass it three arguments.
However, at this point you will find that the compiler will insist that Type1, Type2 and Type3 are all the same type, as lists in F# are constrained to hold values of a single type. You will also get a warning of an incomplete pattern match, as your function does not accommodate lists with an odd number of values.
Without knowing more about the problem you are attempting to serve, I'm not sure what the best solution to those problems would be.

Related

How do I check if the path from a node to another has a depth equal to a given one in a graph in OCaml?

First of all, I'm sorry for how I wrote my question.
Anyway, I'm trying to write a function in OCaml that, given a graph, a max depth, a starting node, and another node, returns the list of the nodes that make the path but only if the depth of it is equal to the given one. However, I can't implement the depth part.
This is what I did:
let m = [(1, 2, "A"); (2, 3, "A");
(3, 1, "A"); (2, 4, "B");
(4, 5, "B"); (4, 6, "C");
(6, 3, "C"); (5, 7, "D");
(6, 7, "D")]
let rec vicini n = function
[] -> []
| (x, y, _)::rest ->
if x = n then y :: vicini n rest
else if y = n then x :: vicini n rest
else vicini n rest
exception NotFound
let raggiungi m maxc start goal =
let rec from_node visited n =
if List.mem n visited then raise NotFound
else if n = goal then [n]
else n :: from_list (n :: visited) (vicini n m)
and from_list visited = function
[] -> raise NotFound
| n::rest ->
try from_node visited n
with NotFound -> from_list visited rest
in start :: from_list [] (vicini start m)
I know I have to add another parameter that increases with every recursion and then check if its the same as the given one, but I don't know where
I am not going to solve your homework, but I will try to teach you how to use recursion.
In programming, especially functional programming, we use recursion to express iteration. In an iterative procedure, there are things that change with each step and things that remain the same on each step. An iteration is well-founded if it has an end, i.e., at some point in time, the thing that changes reaches its foundation and stops. The thing that changes on each step, is usually called an induction variable as the tribute to the mathematical induction. In mathematical induction, we take a complex construct and deconstruct it step by step. For example, consider how we induct over a list to understand its length,
let rec length xs = match xs with
| [] -> 0
| _ :: xs -> 1 + length xs
Since the list is defined inductively, i.e., a list is either an empty list [] or a pair of an element x and a list, x :: list called a cons. So to discover how many elements in the list we follow its recursive definition, and deconstruct it step by step until we reach the foundation, which is, in our case, the empty list.
In the example above, our inductive variable was the list and we didn't introduce any variable that will represent the length itself. We used the program stack to store the length of the list, which resulted in an algorithm that consumes memory equivalent to the size of the list to compute its length. Doesn't sound very efficient, so we can try to devise another version that will use a variable passed to the function, which will track the length of the list, let's call it cnt,
let rec length cnt xs = match xs with
| [] -> cnt
| _ :: xs -> length (cnt+1) xs
Notice, how on each step we deconstruct the list and increment the cnt variable. Here, call to the length (cnt+1) xs is the same as you would see in an English-language explanation of an algorithm that will state something like, increment cnt by one, set xs to the tail xs and goto step 1. The only difference with the imperative implementation is that we use arguments of a function and change them on each call, instead of changing them in place.
As the final example, let's devise a function that checks that there's a letter in the first n letters in the word, which is represented as a list of characters. In this function, we have two parameters, both are inductive (note that a natural number is also an inductive type that is defined much like a list, i.e., a number is zero or the successor of a number). Our recursion is also well-founded, in fact, it even has two foundations, the 0 length and the empty list, whatever comes first. It also has a parameter that doesn't change.
let rec has_letter_in_prefix letter length input =
length > 0 && match input with
| [] -> false
| char :: input ->
char = letter || has_letter_in_prefix letter (length-1) input
I hope that this will help you in understanding how to encode iterations with recursion.

Non-total functions are treated as constants at the type level?

In Type-Driven Development with Idris, ch 6, he says
Type-level functions exist at compile time only ...
Only functions that are total will be evaluated at the type level. A function that isn't total may not terminate, or may not cover all possible inputs. Therefore, to ensure that type-checking itself terminates, functions that are not total are treated as constants at the type level, and don't evaluate further.
I'm having difficulty understanding what the second bullet point means.
How could the type checker claim the code type checks if there's a function that isn't total in its signature? Wouldn't there by definition be some inputs for which the type isn't defined?
When he says constant, does he mean in the same sense as in the docs, like
one: Nat
one = 1
is a constant? If so, how could that enable the type checker to complete its job?
If a type-level function exists at compile time only, does it ever get evaluated if it's not total? If not, what purpose does it serve?
Partial type-level functions are treated as constants in the Skolem sense: invocations of a partial function f remain f with no further meaning.
Let's see an example. Here f is a partial predecessor function:
f : Nat -> Nat
f (S x) = x
If we then try to use it in a type, it will not reduce, even though f 3 would reduce to 2:
bad : f 3 = 2
bad = Refl
When checking right hand side of bad with expected type
f 3 = 2
Type mismatch between
2 = 2 (Type of Refl)
and
f 3 = 2 (Expected type)
So f is an atomic constant here, standing only for itself. Of course, because it does stand for itself, the following still typechecks:
good : f 3 = f 3
good = Refl

Isabelle function to find the longest sequence of members of a relation

I have a relation R :: w => w => bool that is both transitive an irreflexive.
I have the axiom Ax1: "finite {x::w. True}". Therefore, for each x there is always a longest sequence of wn R ... R w2 R w1 R x.
I need a function F:: w => nat, that -for a given x - gives back the "lenght" of this sequence (or 0 if there is no y such that xRy). How would I go about building one in isabelle.
Also: Is Ax1 a good way to axiomatize the "finiteness of type w" or is there a better one?
First of all, a more idiomatic way of writing {x::w. True} is UNIV :: w set. I suggest writing finite (UNIV :: w set), or possibly using the finite type class, although that might make your theorem more difficult to apply because you need a finite instance for your type. I think it's not really necessary or helpful for your use case.
I then suggest the following approach:
Define an inductive predicate (using inductive) on lists of type w list stating that the first element is x and for each two successive list elements y and z, R y z holds, i.e. the list is an ascending chain w.r.t. R.
Show that any list that is such a chain must have distinct elements (cf. distinct :: 'a list ⇒ bool).
Show that there are finitely many distinct lists over a finite set.
Use the Max operator to find the biggest n such that there exists a list of length n that is an ascending chain w.r.t. R. That this works should be easy since there is at least one such chain, and you've already shown that there are only finitely many chains.

Functions with the same name but different arguments in functional languages

I see this code in the example of Elixir:
defmodule Recursion do
def print_multiple_times(msg, n) when n <= 1 do
IO.puts msg
end
def print_multiple_times(msg, n) do
IO.puts msg
print_multiple_times(msg, n - 1)
end
end
Recursion.print_multiple_times("Hello!", 3)
I see here the same function defined twice with different arguments, and I want to understand this technique.
Can I look at them as at overloaded functions?
Is it a single function with different behavior or are these two different functions, like print_only_once and print_multiple_times?
Are these functions linked anyhow or not?
Usually in functional languages a function is defined by clauses. For example, one way to implement Fibonacci in an imperative language would be the following code (not the best implementation):
def fibonacci(n):
if n < 0:
return None
if n == 0 or n == 1:
return 1
else:
return fibonacci(n - 1) + fibonacci(n - 2)
To define the function in Elixir you would do the following:
defmodule Test do
def fibonacci(0), do: 1
def fibonacci(1), do: 1
def fibonacci(n) when n > 1 do
fibonacci(n-1) + fibonacci(n - 2)
end
def fibonacci(_), do: nil
end
Test.fibonacci/1 is only one function. A function with four clauses and arity of 1.
The first clause matches only when the number is 0.
The second clause matches only when the number is 1.
The third clause matches with any number greater than 1.
The last clause matches anything (_ is used when the value of the variable is not going to be used inside the clause or is not relevant for the match).
The clauses are evaluated in the order they are declared, so for Test.fibonacci(2) will fail in the first 2 clauses and match the third one because 2 > 1.
Think of clauses as a more powerful if statement. The code looks cleaner this way. And is very useful for recursion. For example, a map implementation (the language already provide one in Enum.map/2):
defmodule Test do
def map([], _), do: []
def map([x | xs], f) when is_function(f) do
[f.(x) | map(xs, f)]
end
end
First clause matches an empty list. No need to apply a function.
Second clause matches a list where the first element (head) is x and the rest of the list (tail) is xs and f is a function. It applies the function to the first element and recursively calls map with the rest of the list.
Calling Test.map([1,2,3], fn x -> x * 2 end) will give you the following output [2, 4, 6]
So, a function in Elixir is defined with one or more clauses where every clause have the same arity as the rest.
I hope this answers your question.
In the example you posted both definitions of the function have the same number of arguments: 2, this "when" thing is a guard, but you can also have definitions with many arguments. First, guards -- they are uses to express what cannot be written as a mere matching, like the second line of the following:
def fac(0), do: 1
def fac(n), when n<0 do: "no factorial for negative numbers!"
def fac(n), do: n*fac(n-1)
-- since it's not possible to express being negative number by just equality/matching.
Btw this fac is a single definition, only with three cases. Notice the coolness of using constant "0" in the position of argument :)
You can think of this as it would be nicer way to write:
def fac(n) do
if n==0, do: 1, else: if n<0, do: "no factorial!", else: n*fac(n-1)
end
or a switch case (which even looks pretty close to the above):
def fa(n) do
case n do
0 -> 1
n when n>0 -> n*fa(n-1)
_ -> "no no no"
end
end
only "looks more fancy". Actually it turns out certain definitions (e.g. parsers, small interpreters) look much better in the former than latter style. Nb guard expressions are very limited (I think you can't use your own function in guard).
Now the real thing, varying number of arguments -- check this out!
def mutant(a), do: a*a
def mutant(a,b), do: a*b
def mutant(a,b,c), do: mutant(a,b)+mutant(c)
e.g.
iex(1)> Lol.mutant(2)
4
iex(2)> Lol.mutant(2,3)
6
iex(3)> Lol.mutant(2,3,4)
22
It works a bit similar like (lambda arg ...) in scheme -- think of mutant as taking all its arguments as a list and matching over it. But this time, elixir treats mutant as 3 functions, mutant/1, mutant/2, and mutant/3 and will refer to them as such.
So, to answer your question: these are not like overloaded functions, but rather scattered/fragmented definitions. You see similar ones in functional languages like miranda, haskell or sml.

Match Comparison OCaml

I have come to love this syntax in OCaml
match myCompare x y with
|Greater->
|Less->
|Equal->
However, it needs 2 things, a custom type, and a myCompare function that returns my custom type.
Would there be anyway to do this without doing the steps above?
The pervasives module seems to have 'compare' which returns 0 if equal, pos int when greater and neg int when less. Is it possible to match those? Conceptually like so (which does not compile):
match myCompare x y with
| (>0) ->
| (0) ->
| (<0) ->
I know I could just use if statements, but pattern matching is more elegant to me. Is there an easy (if not maybe standard) way of doing this?
Is there an easy … way of doing this?
No!
The advantage of match over what switch does in another language is that OCaml's match tells you if you have thought of covering all the cases (and it allows to match in-depth and is compiled more efficiently, but this could also be considered an advantage of types). You would lose the advantage of being warned if you do something stupid, if you started using arbitrary conditions instead of patterns. You would just end up with a construct with the same drawbacks as a switch.
This said, actually, Yes!
You can write:
match myCompare x y with
| z when (z > 0) -> 0
| 0 -> 0
| z when (z < 0) -> 0
But using when makes you lose the advantage of being warned if you do something stupid.
The custom type type comparison = Greater | Less | Equal and pattern-matching over the three only constructors is the right way. It documents what myCompare does instead of letting it return an int that could also, in another language, represent a file descriptor. Type definitions do not have any run-time cost. There is no reason not to use one in this example.
You can use a library that already provide those variant-returning compare functions. This is the case of the BatOrd module of Batteries, for example.
Otherwise your best bet is to define the type and create a conversion function from integers to comparisons.
type comparison = Lt | Eq | Gt
let comp n =
if n < 0 then Lt
else if n > 0 then Gt
else Eq
(* ... *)
match comp (Pervasives.compare foo bar) with
| Lt -> ...
| Gt -> ...
| Eq -> ...

Resources