Docsity

appunti per parte pratica programmazione funzionale, Appunti di Analisi Funzionale

Toggle sidebar
bg1
Pratica prog funzionale
rlwrap poly
altgr e ì
-come scrivere commenti:
(* maximum of reals *)
Operazioni in ML:
● + e –
● *, / (divisioni tra real), div (divisioni tra int), mod
● ~ (meno unario, su linux altgr + ì)
Concatenazione tra stringhe: ^
> "house" ^ "cat";
val it = "housecat": string
Operatori di confronto: >, <, >=, <=, =, <> (diverso)
Operazioni logiche (lazy evaluation):
● not
● andalso (and): se il primo operando è false, allora si ferma e ritorna false
● orelse (or): se il primo operando è true, si ferma e ritorna true
Conversioni:
- real(): int → real
- da reale a int:
- floor(): real → int (arrotonda per difetto)
- ceil(): real → int (arrotonda per eccesso)
- round(): real → int (arrotonda all’intero più vicino; se la pt decimale è .5,
arrotonda all’intero pari più vicino)
- trunc(): real → int (tronca)
esempi:
▪ 123.45 arrotondare verso il basso→ floor(123.45);
▪ -123.45 to the next lower integer → floor(~123.45);
▪ 123.45 to the next higher integer → ceil(123.45);
▪ -123.45 to the next higher integer ceil(~123.45);
- da char a int e viceversa:
- ord(): char → int
- chr(): int → char
- da char a string:
- str(): char → string
- -toString trasforma int bool e real in stringa
- es.
- print (Bool.toString(true));
- se do val esadecimale ritorna int:
> 0xab;
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22

Anteprima parziale del testo

Scarica appunti per parte pratica programmazione funzionale e più Appunti in PDF di Analisi Funzionale solo su Docsity!

Pratica prog funzionale

rlwrap poly altgr e ì -come scrivere commenti: (* maximum of reals *)

Operazioni in ML: ● + e – ● *, / (divisioni tra real), div (divisioni tra int), mod ● ~ (meno unario, su linux altgr + ì)

Concatenazione tra stringhe: ^ > "house" ^ "cat"; val it = "housecat": string Operatori di confronto: >, <, >=, <=, =, <> (diverso)

Operazioni logiche (lazy evaluation): ● not ● andalso (and): se il primo operando è false, allora si ferma e ritorna false

● orelse (or): se il primo operando è true, si ferma e ritorna true

Conversioni:

  • real(): int → real
  • da reale a int:
  • floor(): real → int (arrotonda per difetto)
  • ceil(): real → int (arrotonda per eccesso)
  • round(): real → int (arrotonda all’intero più vicino; se la pt decimale è .5,

arrotonda all’intero pari più vicino)

  • trunc(): real → int (tronca)

esempi: ▪ 123.45 arrotondare verso il basso→ floor(123.45); ▪ -123.45 to the next lower integer → floor(~123.45); ▪ 123.45 to the next higher integer → ceil(123.45); ▪ -123.45 to the next higher integer ceil(~123.45);

  • da char a int e viceversa:
  • ord(): char → int
  • chr(): int → char
  • da char a string:
  • str(): char → string
    • -toString trasforma int bool e real in stringa
    • es.
    • print (Bool.toString(true));
  • se do val esadecimale ritorna int: > 0xab;

val it = 171: int

Write the expression to convert ▪ #”Y” to an integer ord( #”Y” ); ▪ 120 to a character chr 120; ▪ 97.0 to a character chr(round(97.0)); ▪ #”N” to a real real(ord(#"N")); ▪ #”Z” to a string str#"Z";

Liste

Accesso all’elemento in testa ad una lista (il primo elemento inserito): > hd();

Accesso a tutta la lista esclusa la testa: > tl ();

Concatenazione di liste (devono essere dello stesso tipo):

> [1,2] @ [3,4];

val it = [1, 2, 3, 4]: int list

Inserimento in testa ad una lista: > 2 :: [3,4]; val it = [2, 3, 4]: int list

Trasformazione di una stringa in una lista di char: > explode ("abcd”); val it = [#"a", #"b", #"c", #"d"]: char list

Trasformazione di una lista di char in una stringa: > implode ([ #"a", #"b", #"c", #"d"]); val it = " abcd ": string

tupla

Accesso agli elementi di una tupla: # ();

> val t = (4, 5.0, "six"); > #1 (t); val it = 4: int

-se non so dim tupla non posso usare #1x(primo elemento) Laboratorio 2

explode(“bar”); pk se scrivi explode ["bar"]; dà errore pk hai scritto string list implode [ #"a", #"b"] ; pk se scrivi implode ( #"a", #"b") ; dà errore pk hai scritto tupla "r"::["a","t"]; pk se scrivi ["r"]::["a","t"]; :: serve per aggiungere un elemento non concatenare una lista

val it = [[[3], [4]], [[6], [8]]]: int list list list

let

val a::b::c::xs = explode(st)

in

str(c)

end;

-SHIFT DI 1

fun cicle(a) = tl(a)@[hd(a)]; // fun cycle(a::xs) = xs@[a];

-MIN E MAX

fun min_max_pair(a:int, b, c) = if(a < b andalso a < c) then if(ba) then (c, b) else (c, a) else if(c>a) then (b, c) else (b, a);

-ARROTONDAMENTO NORMALE:

> fun rnd(a:real) =real(round(a*10.0))/10.0;

reverse: > fun reverse L = if L = nil then nil else reverse (tl L) @ [hd L];

laboratorio 3

fattoriale fun fact(n) = if(n = 1) then 1 else n * fact(n-1); fun fact(1) = 1

|fact(x)= x*fact(x-1);

shift tot giri: fun cyclei(i:int, L) = if i = 0 then L else cyclei(i-1, tl(L)@[hd(L)]);

duplica elementi lista fun duplicate(L) = if L = nil then L else [hd(L), hd(L)]@ duplicate(tl(L));

fun duplicate(nil) = nil

|duplicate(a::xs)= a::a::duplicate(xs);

lunghezza lista:

fun len(l) = if l = nil then 0 else 1+len(tl(l));

potenza: fun pow(a:real, b) = if b = 0 then 1.0 else a*(pow(a, b-1));

massima stringa: fun max(L: string list) = if tl(L) = nil then hd(L) else if(hd(L)> hd(tl(L))) then max(hd(L)::tl(tl(L))) else max(tl(L));

> fun maxList(a::nil) = a

|maxList(a:string list) = if hd(a) > maxList(tl(a)) then hd(a) else maxList(tl(a));

CON PATTERN MATCHING:

fattoriale : fun fact (0) = 1 | fact(x) = x*fact(x-1);

shift tot volte: fun cycleip(nil, y) = nil | cycleip(list, 0) = list | cycleip(x::xs, y) = cycleip(xs@[x], y-1);

duplica elementi lista: fun duplicatep(nil) = nil | duplicatep(x::xs) = [x, x]@duplicatep(xs);

potenza: fun power(x:real, 0) = 1. | power(x:real, y) = x*power(x, y-1);

max int in lista: fun maxList(nil) = 0 | maxList [x] = x | maxList(x::y::xs) = if(x > y) then maxList(x::xs) else maxList(y::xs);

fun vowel(nil) = false | vowel( #"a"::xs) = true | vowel( #"e"::xs) = true | vowel( #"i"::xs) = true | vowel( #"o"::xs) = true | vowel( #"u"::xs) = true | vowel(_) = false;

è presente elemento in lista?

fun member(a, nil) = false | member(a, b::xs) = if (a = b) then true else member(a, xs);

delete toglie dalla lista elementi = a quello inserito

fun delete(a, nil) = nil | delete(a, b::xs) = if(a = b) then xs else b::delete(a, xs);

insert inserisce elemento in coda se non è già presente

fun insert(a, nil) = [a] | insert(a, x::xs) = if (a = x) then x::xs else[ x]@insert(a, xs); inserisce in tutte le liste della lista l’elemento, ex. insertAll (1,[[2,3],[],[3]]) = [[1,2,3],[1],[1,3]]

fun insertAll(a, nil) = nil | insertAll(a, x::xs) = [a::x]@insertAll(a, xs);

> fun insertAll(a,nil) = nil | insertAll(a,L::Ls) = (a::L)::insertAll(a,Ls);

insieme delle parti, ex. powerSet([1,2,3])=[[],[1],[2],[3],[1,2],[1,3],[2 ,3],[1,2,3]]

fun powerSet(nil) = [nil] |powerSet(x::xs) = powerSet(xs)@insertAll(x,powerSet(xs));

prodotto differenza

> fun aux (nil:real list) = 1.

|aux([x])= 1. | aux(x::y::xs) = (x-y)*aux(x::xs);

> fun prodDiff (nil) = 1. | prodDiff([x]) = 1.

| prodDiff(x::xs) = aux(x::xs)* prodDiff(xs);

function is_one that returns “one” if the parameter is 1 and “anything else” otherwise.

> fun is_one (1) = "one" | is_one(x) = "anything else";

con case:

> val is_one = fn n => case n of 1 =>"one" | _ => "anything else";

con fun:

> fun is_one(n) = case n of 1 =>"one" | _ => "anything else";

Mutual recursion

-2 funzioni che si chiamano a vicenda →usare costrutto and

Pattern matching

x::xs →catura lista con almeno un elemento

-la lista di istruzioni deve essere esaustiva non riusciamo a catturare con pattern matching: ● concatenazione liste (@) ● costanti con valori reali matching con (0.0) ● operazioni aritmetiche

-as per tenere nome dell’argomento, esempio:

fun filter (P,nil) = nil | filter (P,x::xs) = if P(x) then x::filter(P,xs) else filter (P,xs);

Output

print(x) →tipo unit (come void)

-non ritorna il tipo del valore stampato

>print(“ab\n”); ab val it = (): unit

-compound → per stampe ma senza necessità di modifica tra le diverse stampe: > ( print(Real.toString(1.0E50)); print(Int.toString(123)) ); il tipo del compound è quello dell’ultima affermazione

Input

-mette contenuto file in infile -funzioni disponibili:

-SOME →t option -NONE →linea vuota (non ci sono più righe da leggere) -lettura intero file:

-leggere singolo char:

> TextIO.input1;

-restituisce NONE se sono finiti i caratteri -restituisce SOME se ci sono char

-leggi prox char ma non passo oltre:

-sono rimasti 50 char? -ne sono rimasti 10

return type: ● inputLine →string option ● input1 → char ● lookahead → char ● canInput →int ● input →string Es. 5.11: > val infile = TextIO.openIn("zap"); (* inizio lettura*)

> TextIO.inputN(infile, 5); (input 5 caratteri)

> TextIO.inputLine(infile); (input riga) > TextIO.lookahead; (*leggere prossimo carattere senza

“consumarlo” *)

> TextIO.input(infile); (*leggere tutto il file *) > TextIO.closeIn(infile);

es. 5.12: fun white(" ") = true | white("\n") = true

| white("\t") = true | white("\r") = true | white(_) = false;

fun getWord(infile) = if(TextIO.endOfStream(infile)) then "" else let

val c = TextIO.inputN (infile, 1 );

eccezioni con parametri >exception of ;

handling (gestione eccezioni)

se trova eccezioni messaggi di errore:

Equality types

-sono i tipi che permettono l’uso di operatori di uguaglianza -’’a = tipo che permettono uso = e <> -int, boolean, char MA non real -tuple, list (di tipi confrontabili) MA non funzioni

per ovviare applico uguaglianza nella funzione ( non applicabile ai reali):

-oppure forzo la conversione:

-operatore null(L) Un modo alternativo per verificare se una lista è vuota, senza costringerla a essere di un tipo confrontabile, è il seguente:

→ così posso usarla con liste di funzioni

Laboratorio 5

-a^1000 con let val fun thousandthPower(a:real) = let val ten = aaaaaaaaaa; val cent = tentententententententententen; in centcentcentcentcentcentcentcentcent*cent end;

-split M elementi in posizioni pari N elementi in posizioni dispari

fun split (nil) = (nil, nil) |split([a]) = ([a], nil) |split (a::b::cs) = let val c = split(cs); in (a::(#1c), b::(#2c)) end;

fun sumList(nil) = (0,0)

|sumList(a::nil) = (a,0) |sumList(a::b::cs) = let val (c,d) = sumList(cs); in (a+c,

b+d) end;

stampa lista di interi: > fun printList(nil) =print( "" ) | printList(a::cs)= (

print(Int.toString(a)^"\n"); printList(cs)

);

stampa combinazioni: > fun comb(a,b) = let

val c = (fact(a)div(fact(b)*fact(a-b)));

in ( print("n is "^(Int.toString(a))^"\n"); print("m is "^(Int.toString(b))^"\n"); print("result is "^(Int.toString(c))^"\n") )

end;

Write a function printXs that given an integer 𝑛, print 2^𝑛 Xs

> fun printXs(0) = print("X")

| printXs(1) = print("xx") |printXs(a) = (printXs(a-1);printXs(a-1));

Laboratorio 6 exception

-ritornare terzo elemento lista ma se troppo corta ritorna errore

>fun dim(nil) = 0 | dim(a::t) = 1+ dim(t);

>exception short of int;

>fun return(a::b::c::t) = c | return(a) = raise short(dim(a));

>fun returnThird(a) = return(a) handle short(b) =>( print("List too short.\n"); print(" It only contains "); print(Int.toString(dim(a))); print( " elements.\n"); 0 );

-fattoriale con messaggio di errore:

exception neg of int;

fun fact1 (0) = 1 | fact1(x) = if (x > 0) then x*fact1(x-1) else raise neg(x);

fun fact(x) = fact1(x) handle neg(a) =>( print("Negative argument "); print(Int.toString(x)); print(" found. \n"); 0 );

-stampare tabella con utilizzo di funzione nella chiamata:

fun tabulate(a, i, 0, F) = print("") |tabulate(a, i, n, F) = ( print(Real.toString(a)^" "); print(Real.toString(F(a))^"\n"); tabulate(a+i, i, n-1, F) );

-utilizzo simpleMap:

>fun simpleMap (F,nil) = nil | simpleMap (F,x::xs) = F(x) :: simpleMap(F,xs);

>fun neg(a:real) = if (a>=0.0) then a else ~a;

>simpleMap(neg, [1.0, 2.0, ~3.4]);

-utilizzo reduce:

> fun applyList nil b = nil

| applyList (x::xs) b = x(b) :: applyList xs b;

> applyList [fn x=>x2, fn x => xx*x] 4;

val it = [8, 64]: int list

funzione curry: > fun curry f = fn x => fn y => fn z => f (x, y, z);

val curry = fn: ('a * 'b * 'c -> 'd) -> 'a -> 'b -> 'c -> 'd

> fun curry f a b c = f(a,b,c); val curry = fn: ('a * 'b * 'c -> 'd) -> 'a -> 'b -> 'c -> 'd

funzioni predefinite in ML:

Operatore op: trasforma operazioni postfisse a prefisse: > reduce (+, [1,2,3]); poly: : warning: (+) has infix status but was not preceded by op. > fun plus (x,y) = x+y; val plus = fn: int * int -> int > reduce(plus, [1,2,3]); val it = 6: int soluzione migliore con op: > reduce (op +, [1,2,3]); val it = 6: int

● map → accetta 2 parametri :una fn e una lista > map (fn x => x + 2) [1,2,3]; val it = [3, 4, 5]: int list

lab esercizio 7.3 utilizzo map :

> fun toreal (a) = real(a);

> val torealList = map toreal;

//val torealList = map (fn a => real(a))

> torealList([1,2,3]);

val it = [1.0, 2.0, 3.0]: real list

lab esercizio 7.4 utilizzo map, e foldl:

> fun fnAnd (a, b) = a andalso b;

> foldr fnAnd true [true, false, true]; //false > foldl fnAnd true [true, true, true]; //true

// non capisco come usare map

● foldr → prende fun val iniziale c e lista di valori : parte dal fondo ad applicare la funzione

● foldl → prende fun val iniziale c e lista di valori: parte dall’inizio ad applicare la funzione

-sono in versione curried

-creare la funzione implode:

val toString = map (fn a => str(a));

fun implode a = foldr (fn (a,b) => a ^ b ) "" (toString a);

> implode [#"a", #"a", #"b"];

val it = "aab": string

fun implode a = foldr (fn (b,xs) => str(b) ^ xs ) "" a;

> fun implodel b = foldl (fn (a, xs) => xs ^ str(a)) "" b;

-funzioni composte