16 aprilie 2010

Functii in Haskell

allEqual a b c =
if a == b && a == c && b == c then True
else False

allDifferent a b c =
if a /= b && a /= c && b /= c then True
else False

howManyEqual a b c
| allEqual a b c = 3
| allDifferent a b c = 0
| otherwise = 2

-- calculeaza sirul fibonacci
fibonacci n
| n == 0 = 1
| n == 1 = 1
| otherwise = fibonacci(n -1) + fibonacci(n - 2)

-- creeaza o pereche ordonata
orderTuple a b
| a > b =(b, a)
| otherwise = (a, b)

-- daca un element apartine listei
member x [] = False
member x (h:t) =
if (h == x) then True
else member x t

-- produs cartezian a doua liste
cartProd a b = [(x,y) | x<-a, y<-b]

-- applies f to every element of list l and returns the new list
functie x = x+2
mapp f [a] = [f a]
mapp f (a:l) =
(f a):(mapp f l)

-- returns a list containing only the elements from list l, satisfying the predicate p
predicat x = x > 2
filterr p (a:l) =
if (p a) then a:(filter p l)
else filter p l

{- reduces a list to a value, going from left to right: applies f to the seed and the first list element,
then applies f to the result and the second element etc -}
f x y= x+y
foldleft f seed [] = seed
foldleft f seed l =
seed + foldleft f (head l) (tail l)

{- computes the sum of list elements, using foldleft -}
sumList l = foldleft f 0 l

{- reduces a list to a value, going from right to left: first computation is (f last_element seed) -}
foldright f elem [] = elem
foldright f seed l =
foldright f (head l) (tail l) + seed

{- returns the number of occurences of val in a, b, c -}
valOccurs val a b c
| a==val = 1+(valOccurs val (1-a) b c)
| b==val = 1+(valOccurs val a (1-b) c)
| c==val = 1+(valOccurs val a b (1-c))
| otherwise = 0

{- returns an ordered triple based on a, b, c -}
orderTriple a b c =
if (a<=b && b<=c) then (a,b,c)
else if (b<=a && a<=c) then (b,a,c)
else if (a<=c && c<=b) then (a,c,b)
else if(b<=c && c<=a) then (b,c,a)
else if (c<=a && a<=b) then (c,a,b)
else (c,b,a)

{- returns the minimum in a list -}
minim a b =
if (a < b) then a
else b
minVal (a:[]) = a
minVal (a:l) =
minim a (minVal l)

{- returns True if all list elements are equal -}
allEq [a] = True
allEq (a:l) =
if (a/= (head l)) then False
else allEq l

{- returns True if list is sorted ascending -}
ascOrd [a] = True
ascOrd (a:l) =
if (a > (head l)) then False
else ascOrd l

{- returns True if list p is a prefix of list l -}
startsWith [] lista = True
startsWith lista [] = False
startsWith p l =
if ((head p) /= (head l)) then False
else startsWith (tail p) (tail l)

{- removes the prefix p from list l -}
del p l =
if (p==[] && l /= []) then l
else del (tail p) (tail l)

{- substitutes all occurences of element old with element new in the list l -}
subst old new [] = []
subst old new (a:l) =
if (a == old) then new:(subst old new l)
else a:(subst old new l)

Niciun comentariu: