0% found this document useful (0 votes)
14 views

ML Programs

The document defines several recursive functions for reversing, summing, finding the maximum, length, and sublists of a list. It also contains functions for interleaving, permuting, selecting elements, and calculating combinations and permutations of a list.

Uploaded by

oyoyyoyo
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

ML Programs

The document defines several recursive functions for reversing, summing, finding the maximum, length, and sublists of a list. It also contains functions for interleaving, permuting, selecting elements, and calculating combinations and permutations of a list.

Uploaded by

oyoyyoyo
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

fun rev([]) = []

| rev(x::xs) = rev(xs)@[x];
fun revl([],M) = M
| revl(x::xs, ys) = revl(xs, x::ys);
fun rev(L) = revl(L, []);
fun suml([], total) = total
| suml(x::xs, total) = suml(xs, x + total);
fun sum(L) = sum(L, 0);
exception NO_LAST_ELEMENT
fun last([x]) = x
| last(x::xs) = last(xs);
fun prod([]) = 1
| prod(x::xs) = x*prod(xs);
fun max([m]) = m
| max(m::n::ns) = if m>n then max(m::ns)
else mas(n::ns);
local
fun lenl(n, []) = n
| lenl(n, x::xs) = lenl(n+1, xs)
in
fun length(L) = lenl(0,L)
end;
fun revtake(_, [], taken) = taken
| revtake(i, x::xs, taken) = if i>0 then revtaketake(i-1, xs, x::taken)
else taken;
fun nest(xlist, y::ys) : int list =
if hd(xlist) <= y then next(y::xlist, ys)
else
let
fun swap([x]) = y::x::ys
| swap(x::xk::xs) = if xk > y then x::
swap(xk::xs)
else (y:
:xk::xs)@(xs::ys)
in
swap(xlist)
end;
fun interleave x [] = [[x]]
| interleave x (h::t) =
(x::h::t)::(List.map(fn l => h::l) (interleave x t))
fun permute nil = [[]]
| permute (h::t) = List.concat( List.map (fn l => interleave h l) (permute t))
fun el(L, 1) = hd(L)
| el(L, n) = el(tl(L), n-1);
fun bin(0) = [0]
| bin(n) = bin(n div 2) @ [n mod 2];

fun comb(_,0) = 1
| comb(n,m) = if m=n then 1
else comb(n-1,m) + comb(n-1,m-1);
fun i(x, []) = [[x]]
| i(x, h::t) = (x::(h::t))::(List.map(fn l => h::l) (i(x, t)));
fun perm([]) = [[]]
| perm(h::t) = List.concat(List.map(fn l => i(h, l)) (perm(t)));
fun trap(a,b,n,F) =
if n<=0 orelse b-a<=0.0 then 0.0
else
let
val delta = (b-a)/real(n)
in
delta*(F(a) + F(a+delta))/2.0 + trap(a+delta,b,n-1,F)
end;

You might also like