Advertisement
pdhg

Untitled

Jan 23rd, 2020
278
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 50.83 KB | None | 0 0
  1. [TOC]
  2.  
  3. #Chestii simple
  4.  
  5. ##Operatii
  6.  
  7. - `/=` diferit
  8. - `==` egal
  9. - `<=` si `>=`
  10. - `rem` restul impartirii
  11. - `div` impartire
  12. - `*` inmultire
  13. - `^` ridicare la putere
  14. - `sqrt` radical
  15.  
  16. ##Liste
  17.  
  18. Se adauga lista la alta lista cu `++`
  19.  
  20. ```haskell
  21. Prelude> [1,2,3] ++ [12]
  22. [1,2,3,12]
  23. ```
  24.  
  25. Se iau elemente din lista cu `:`
  26.  
  27. ```haskell
  28. -- Double every second number in a list starting on the left.
  29. doubleEveryOther :: [Integer] -> [Integer]
  30. doubleEveryOther [] = []
  31. doubleEveryOther [x] = [x]
  32. doubleEveryOther (x : y : ls) = x : 2 * y : doubleEveryOther(ls)
  33. ```
  34.  
  35. ##Multimi
  36.  
  37. ```haskell
  38. -- Sa se determine toate sirurile s = xy obtinute dintr­-o lista xs
  39. -- cu proprietatea ca x si y apartin listei xs si sirul s e palindom.
  40. -- (ex. pal ["say", "on", "not", "to", "as"] = ["sayas","noton","tonot"])
  41. pal :: [String] -> [String]
  42. pal ls = [x ++ y | x <- ls, y <- ls, reverse(x ++ y) == x ++ y]
  43. ```
  44.  
  45. ##Map
  46.  
  47. Aplica functie fiecarui element din lista `map functie lista`.
  48. Merge apelata si ca `functie `map` lista`.
  49.  
  50. ```haskell
  51. Prelude Data.Char> map toUpper "teSt"
  52. "TEST"
  53.  
  54. Prelude > map (\x -> x * x) [1, 2, 3, 4, 5]
  55. [1, 4, 9, 16, 25]
  56.  
  57. Prelude Data.Char> toLower `map` "AbCCADAS"
  58. "abccadas"
  59.  
  60. ##Filter
  61.  
  62. Returneaza numai elementele ce trec prin filtru.
  63.  
  64. ```haskell
  65. Prelude> filter(/= 'a') "aAAbcsa"
  66. "AAbcs"
  67.  
  68. Prelude> filter(== 1) [1, 12, 1, 14]
  69. [1,1]
  70.  
  71. Prelude Data.Char> filter(isLetter) "1a2b3c5d"
  72. "abcd"
  73. ```
  74.  
  75. ##Foldl si prietenii
  76.  
  77. ```haskell
  78. foldr functie element_initial (1:2:3:[]) = 1 `functie` (2 `functie` (3 `functie` element_initial))
  79.  
  80. Prelude> foldl (+) 0 [1,2,3,4,5]
  81. 15
  82.  
  83. foldl (-) 100 [1] = 99 = ((100)-1)
  84. foldl (-) 100 [1,2] = 97 = (( 99)-2) = (((100)-1)-2)
  85. foldl (-) 100 [1,2,3] = 94 = (( 97)-3)
  86. foldl (-) 100 [1,2,3,4] = 90 = (( 94)-4)
  87. foldl (-) 100 [1,2,3,4,5] = 85 = (( 90)-5)
  88.  
  89. Prelude> foldr (\x y -> concat ["(", x, "+", y, ")"]) "0" (map show [1..13])
  90. "(1+(2+(3+(4+(5+(6+(7+(8+(9+(10+(11+(12+(13+0)))))))))))))"
  91.  
  92. Prelude> foldl (\x y -> concat ["(", x, "+", y, ")"]) "0" (map show [1..13])
  93. "(((((((((((((0+1)+2)+3)+4)+5)+6)+7)+8)+9)+10)+11)+12)+13)"
  94.  
  95. Prelude> foldt (\x y -> concat ["(", x, "+", y, ")"]) "0" (map show [1..13])
  96. "((((1+2)+(3+4))+((5+6)+(7+8)))+(((9+10)+(11+12))+13))"
  97.  
  98. Prelude> foldi (\x y -> concat ["(", x, "+", y, ")"]) "0" (map show [1..13])
  99. "(1+((2+3)+(((4+5)+(6+7))+((((8+9)+(10+11))+(12+13))+0))))"
  100. ```
  101.  
  102. #Tipuri de date algebrice
  103.  
  104. Pot sa fie absolut orice.
  105.  
  106. ```haskell
  107. data Bool = False | True
  108. data Season = Winter | Spring | Summer | Fall
  109. data Shape = Circle Float | Rectangle Float Float
  110. data List a = Nil | Cons a (List a)
  111. data Nat = Zero | Succ Nat
  112. data Exp = Lit Int | Add Exp Exp | Mul Exp Exp
  113. data Tree a = Empty | Leaf a | Branch (Tree a) (Tree a) data Maybe a = Nothing | Just a
  114. data Pair a b = Pair a b
  115. data Either a b = Left a | Right b
  116. ```
  117.  
  118. ##Anotimpuri
  119.  
  120. ```haskell
  121. data Season = Spring | Summer | Autumn | Winter
  122.  
  123. next :: Season -> Season
  124. next Spring = Summer
  125. next Summer = Autumn
  126. next Autumn = Winter
  127. next Winter = Spring
  128.  
  129. eqSeason :: Season -> Season -> Bool
  130. eqSeason Spring Spring = True
  131. eqSeason Summer Summer = True
  132. eqSeason Autumn Autumn = True
  133. eqSeason Winter Winter = True
  134. eqSeason _ _ = False
  135.  
  136. showSeason :: Season -> String
  137. Spring = " Spring "
  138. Summer = " Summer "
  139. Autumn = " Autumn "
  140. Winter = " Winter "
  141.  
  142. data Season = Winter | Spring | Summer | Fall
  143.  
  144. toInt :: Season -> Int
  145. toInt Winter = 0
  146. toInt Spring = 1
  147. toInt Summer = 2
  148. toInt Fall = 3
  149.  
  150. fromInt :: Int -> Season
  151. fromInt 0 = Winter
  152. fromInt 1 = Spring
  153. fromInt 2 = Summer
  154. fromInt 3 = Fall
  155.  
  156. next :: Season -> Season
  157. next x = fromInt ((toInt x + 1) `mod` 4)
  158. ```
  159.  
  160. ##Cercuri si dreptunghiuri
  161.  
  162. ```haskell
  163. type Radius = Float
  164. type Width = Float
  165. type Height = Float
  166.  
  167. data Shape = Curclr Radius
  168. | Rectangle Width Height
  169.  
  170. area :: Shape -> Float
  171. area (Circle r) = pi * r^2
  172. area (Rectangle w h) = w * h
  173.  
  174. eqShape :: Shape -> Shape -> Bool
  175. eqShape (Circle r) (Circle r2) = (r == r2)
  176. eqShape (Rectangle w h) (Rectangle w2 h2) = (w == w2) && (h == h2)
  177. eqShape _ _ = False
  178.  
  179. isCircle :: Shape -> Bool
  180. isCircle ( Circle r ) = True
  181. isCircle _ = False
  182.  
  183. isRectangle :: Shape -> Bool
  184. isRectangle ( Rectangle w h ) = True
  185. isRectangle _ = False
  186.  
  187. radius :: Shape -> Float
  188. radius (Circle r) = r
  189.  
  190. width :: Shape -> Float
  191. width (Rectangle w h) = w
  192.  
  193. height :: Shape -> Float
  194. height (Rectangle w h) = h
  195.  
  196. area :: Shape -> Float
  197. area (Circle r) = pi * r^2
  198. area (Rectangle w h) = w * h
  199.  
  200. area :: Shape -> Float
  201. area s =
  202. if isCircle s then
  203. let
  204. r = radius s
  205. in
  206. pi * r^2
  207. else if isRectangle s then
  208. let
  209. w = width s
  210. h = height s
  211. in
  212. w * h
  213. else error " impossible "
  214. ```
  215.  
  216. ##Expresii - curs
  217.  
  218. ###Expresii
  219.  
  220. ```haskell
  221. data Exp = Lit Int
  222. | Add Exp Exp
  223. | Mul Exp Exp
  224.  
  225.  
  226. evalExp :: Exp -> String
  227. evalExp (Lit n) = n
  228. evalExp (Add e f) = evalExp e + evalExp f
  229. evalExp (Mul e f) = evalExp e * evalExp f
  230.  
  231. showExp :: Exp -> String
  232. showExp (Lit n) = show n
  233. showExp (Add e f) = par (showExp e ++ "+" ++ showExp f)
  234. showExp (Mul e f) = par (showExp e ++ "*" ++ showExp f)
  235.  
  236. par :: String -> String
  237. par s = "(" ++ s ++ ")"
  238. ```
  239.  
  240. ```haskell
  241. e0, e1 :: Exp
  242.  
  243. e0 = Add (Lit 2) (Mul (Lit 3) (Lit 3))
  244. e1 = Mul (Add (Lit 2) (Lit 3)) (Lit 3)
  245.  
  246. *Main> showExp e0
  247. " (2+(3*3) ) "
  248.  
  249. * Main> evalExp e0
  250. 11
  251.  
  252. *Main> showExp e1
  253. " ((2+3) *3) "
  254.  
  255. * Main> evalExp e1
  256. 15
  257. ```
  258.  
  259.  
  260. ###Expresii - forma infixata
  261.  
  262. ```haskell
  263. data Exp = Lit Int
  264. | Exp `Add` Exp
  265. | Exp `Mul` Exp
  266.  
  267. evalExp :: Exp -> Int
  268. evalExp (Lit n) = n
  269. evalExp (e ‘Add‘ f) = evalExp e + evalExp f
  270. evalExp (e ‘Mul‘ f) = evalExp e * evalExp f
  271.  
  272. showExp :: Exp -> String
  273. showExp (Lit n) = show n
  274. showExp (e `Add` f) = par (showExp e ++ "+" ++ showExp f)
  275. showExp (e `Mul` f) = par (showExp e ++ "*" ++ showExp f)
  276.  
  277. par :: String -> String
  278. par s = "(" ++ s ++ ")"
  279. ```
  280.  
  281. ```haskell
  282. e0, e1 :: Exp
  283.  
  284. e0 = Lit 2 ‘Add‘ (Lit 3 ‘Mul‘ Lit 3)
  285. e1 = (Lit 2 ‘Add‘ Lit 3) ‘Mul‘ Lit 3
  286.  
  287. *Main> showExp e0
  288. " (2+(3*3) ) "
  289.  
  290. * Main> evalExp e0
  291. 11
  292.  
  293. *Main> showExp e1
  294. " ((2+3) *3) "
  295.  
  296. * Main> evalExp e1
  297. 15
  298. ```
  299.  
  300.  
  301.  
  302. ###Expresii - cu operatori
  303. ```haskell
  304. data Exp = Lit Int
  305. | Exp :+: Exp
  306. | Exp :*: Exp
  307.  
  308. evalExp :: Exp -> Int
  309. evalExp (Lit n) = n
  310. evalExp (e :+: f) = evalExp e + evalExp f
  311. evalExp (e :*: f) = evalExp e * evalExp f
  312.  
  313. showExp :: Exp -> String
  314. showExp (Lit n) = show n
  315. showExp (e :+: f) = par (showExp e ++ "+" ++ showExp f)
  316. showExp (e :*: f) = par (showExp e ++ "*" ++ showExp f)
  317.  
  318. par :: String -> String
  319. par s = "(" ++ s ++ ")"
  320. ```
  321.  
  322. ```haskell
  323. e0, e1 :: Exp
  324.  
  325. e0 = Lit 2 :+: (Lit 3 :*: Lit 3)
  326. e1 = (Lit 2 :+: Lit 3) :*: Lit 3
  327.  
  328. *Main> showExp e0
  329. " (2+(3*3) ) "
  330.  
  331. * Main> evalExp e0
  332. 11
  333.  
  334. *Main> showExp e1
  335. " ((2+3) *3) "
  336.  
  337. * Main> evalExp e1
  338. 15
  339. ```
  340.  
  341.  
  342. ##Exercitii
  343.  
  344. ###Mere si portocale
  345.  
  346. ```haskell
  347. -- The datatype 'Fruit'
  348. data Fruit = Apple(String, Bool)
  349. | Orange(String, Int)
  350.  
  351. -- Some example Fruit
  352. apple, apple', orange :: Fruit
  353. apple = Apple("Granny Smith", False) -- a Granny Smith apple with no worm
  354. apple' = Apple("Braeburn", True) -- a Braeburn apple with a worm
  355. orange = Orange("Sanguinello", 10) -- a Sanguinello with 10 segments
  356.  
  357. fruits :: [Fruit]
  358. fruits = [Orange("Seville", 12),
  359. Apple("Granny Smith", False),
  360. Apple("Braeburn", True),
  361. Orange("Sanguinello", 10)]
  362.  
  363. -- This allows us to print out Fruit in the same way we print out a list, an Int or a Bool.
  364.  
  365. instance Show Fruit where
  366. show (Apple(variety, hasWorm)) = "Apple(" ++ variety ++ ", " ++ show hasWorm ++ ")"
  367. show (Orange(variety, segments)) = "Orange(" ++ variety ++ ", " ++ show segments ++ ")"
  368.  
  369.  
  370. isBloodOrange :: Fruit -> Bool
  371. isBloodOrange (Orange (b, c)) = if b `elem` ["Tarocco", "Moro", "Sanguinello"]
  372. then True
  373. else False
  374. isBloodOrange _ = False
  375.  
  376. getNumberOfSlices :: Fruit -> Int
  377. getNumberOfSlices (Apple (b, c)) = 0
  378. getNumberOfSlices (Orange (b, c)) = c
  379.  
  380. bloodOrangeSegments :: [Fruit] -> Int
  381. bloodOrangeSegments xs = foldl (+) 0 (getNumberOfSlices `map` (filter isBloodOrange xs))
  382.  
  383. -- [Orange("Seville", 12), Orange("Moro", 11), Apple("Granny Smith", False), Apple("Braeburn", True), Orange("Sanguinello", 10)]
  384.  
  385. isAppleWithWorm :: Fruit -> Bool
  386. isAppleWithWorm (Apple (_, True)) = True
  387. isAppleWithWorm _ = False
  388.  
  389. worms :: [Fruit] -> Int
  390. worms xs = length (filter isAppleWithWorm xs)
  391. ```
  392.  
  393. ###Expresii
  394.  
  395. The following data type represents arithmetic expressions over a single variable:
  396.  
  397. ```haskell
  398. data Expr = X -- variable
  399. | Const Int -- integer constant
  400. | Expr :+: Expr -- addition
  401. | Expr :-: Expr -- substraction
  402. | Expr :*: Expr -- multiplication
  403. | Expr :/: Expr -- integer division
  404. | IfZero Expr Expr Expr -- conditional expression
  405. ```
  406.  
  407. `IfZero p q r` represents the expression that would be written in Haskell as if `p == 0 then q else r`.
  408.  
  409. 1. Write a function `eval :: Expr -> Int -> Int`, which given an expression and the value of the variable `X` returns the value of the expression. For example:
  410.  
  411. ```haskell
  412. eval (X :+: (X :*: Const 2)) 3 = 9
  413. eval (X :/: Const 3) 7 = 2
  414. eval (IfZero (X :-: Const 3) (X:/:X) (Const 7)) 3 = 1
  415. eval (IfZero (X :-: Const 3) (X:/:X) (Const 7)) 4 = 7
  416. eval (Const 15 :-: (Const 7 :/: (X :-: Const 1))) 0 = 22
  417. ```
  418.  
  419. but both of the following should produce a divide-by-zero exception:
  420.  
  421. ```haskell
  422. eval (Const 15 :-: (Const 7 :/: (X :-: Const 1))) 1
  423. eval (X :/: (X :-: X)) 2
  424. ```
  425.  
  426. 2. Write a function `protect :: Expr -> Expr` that protects against divide-by-zero exceptions by "guarding" all uses of division with a test for a zero-valued denominator. In this case the result should be `maxBound` (the maximum value of type `Int`, which is platform dependent). Do not attempt to simplify the result by omitting tests that appear to be unnecessary. For example,
  427.  
  428. ```haskell
  429. protect (X :+: (X :*: Const 2))
  430. = (X :+: (X :*: Const 2))
  431.  
  432. eval (protect (X :+: (X :*: Const 2))) 3 = 9
  433. ```
  434.  
  435. ```haskell
  436. protect (X :/: Const 3)
  437. = IfZero (Const 3) (Const maxBound) (X :/: Const 3)
  438.  
  439. eval (protect (X :/: Const 3)) 7 = 2
  440. ```
  441.  
  442. ```haskell
  443. eval (protect (X :/: (X :-: X))) 2 = maxBound
  444. ```
  445. ####Afisarea
  446.  
  447. ```haskell
  448. showExpr :: Expr -> String
  449. showExpr X = "X"
  450. showExpr (Const n) = show n
  451. showExpr (p :+: q) = "(" ++ showExpr p ++ "+" ++ showExpr q ++ ")"
  452. showExpr (p :-: q) = "(" ++ showExpr p ++ "-" ++ showExpr q ++ ")"
  453. showExpr (p :*: q) = "(" ++ showExpr p ++ "*" ++ showExpr q ++ ")"
  454. showExpr (p :/: q) = "(" ++ showExpr p ++ "/" ++ showExpr q ++ ")"
  455. showExpr (IfZero p q r) = "(if " ++ showExpr p ++ " = 0 then "
  456. ++ showExpr q ++ "
  457. else "++ showExpr r ++ ")"
  458. ```
  459.  
  460. ####Evaluarea
  461.  
  462. ```haskell
  463. eval :: Expr -> Int -> Int
  464. eval X v = v
  465. eval (Const n) _ = n
  466. eval (p :+: q) v = (eval p v) + (eval q v)
  467. eval (p :-: q) v = (eval p v) - (eval q v)
  468. eval (p :*: q) v = (eval p v) * (eval q v)
  469. eval (p :/: q) v = (eval p v) `div` (eval q v)
  470. eval (IfZero p q r) v = if (eval p v) == 0 then eval q v else eval r v
  471. ```
  472.  
  473. ####Protectie pentru impartirea la 0
  474.  
  475. ```haskell
  476. protect :: Expr -> Expr
  477. protect X = X
  478. protect (Const n) = (Const n)
  479. protect (p :+: q) = (protect p) :+: (protect q)
  480. protect (p :-: q) = (protect p) :-: (protect q)
  481. protect (p :*: q) = (protect p) :*: (protect q)
  482. protect (p :/: q) = IfZero (protect q) (Const maxBound) ((protect p) :/: (protect q))
  483. protect (IfZero p q r) = IfZero (protect p) (protect q) (protect r)
  484. ```
  485.  
  486. ###Arbori
  487.  
  488. Consider binary trees with `Int`-labelled nodes and leaves, defined as follows:
  489.  
  490. ```haskell
  491. data Tree = Empty
  492. | Leaf Int
  493. | Node Tree Int Tree
  494. ```
  495.  
  496. and the following example of a tree:
  497.  
  498. ```
  499. t = Node (Node (Node (Leaf 1)
  500. 2
  501. Empty)
  502. 3
  503. (Leaf 4))
  504. 5
  505. (Node Empty
  506. 6
  507. (Node (Leaf 7)
  508. 8
  509. (Leaf 9)))
  510. ```
  511.  
  512. Each label in a tree can be given an "address": this is the path from the root to the label, consisting of a list of directions:
  513.  
  514. ```haskell
  515. data Direction = L | R
  516. type Path = [Direction]
  517. ```
  518.  
  519. The empty path refers to the label at the root — in `t` above, the label `5`. A path beginning with L refers to a label in the left, or first, subtree, and a path beginning with R refers to the right, or second, subtree. Subsequent L/R directions in the list then refer to left/right subtrees of that subtree. So, for example, `[R,R,L]` is the address of the label 7 in `t`.
  520.  
  521. ####Verifica daca exista calea in arbore
  522.  
  523. ```haskell
  524. present :: Path -> Tree -> Bool
  525. present [] (Leaf n) = True
  526. present [] (Node _ n _) = True
  527. present (L:p) (Node t _ _) = present p t
  528. present (R:p) (Node _ _ t) = present p t
  529. present _ _ = False
  530. ```
  531.  
  532. ####Returneaza valoarea unui nod din arbore
  533.  
  534. ```haskell
  535. label :: Path -> Tree -> Int
  536. label [] (Leaf n) = n
  537. label [] (Node _ n _) = n
  538. label (L:p) (Node t _ _) = label p t
  539. label (R:p) (Node _ _ t) = label p t
  540. label _ _ = error "path absent"
  541. ```
  542.  
  543. ####Convertire abore in drumuri
  544.  
  545. ```haskell
  546. toFTree' :: Tree -> FTree
  547. toFTree' (Leaf n) [] = n
  548. toFTree' (Node t1 n t2) [] = n
  549. toFTree' (Node t1 n t2) (L:p) = toFTree' t1 p
  550. toFTree' (Node t1 n t2) (R:p) = toFTree' t2 p
  551. toFTree' _ _ = error "path absent"
  552. ```
  553.  
  554. ####Construirea arborelui in oglinda
  555.  
  556. ```haskell
  557. mirrorTree :: Tree -> Tree
  558. mirrorTree Empty = Empty
  559. mirrorTree (Leaf n) = Leaf n
  560. mirrorTree (Node t1 n t2) = Node (mirrorTree t2) n (mirrorTree t1)
  561. ```
  562.  
  563. ####Evaluarea adancimii celei mai indepartate frunze din arbore
  564.  
  565. ```haskell
  566. leafdepth :: Tree -> Int
  567. leafdepth Empty = 0
  568. leafdepth (Leaf n) = 1
  569. leafdepth (Node t t') | d == 0 && d' == 0 = 0
  570. | otherwise = 1 + max d d'
  571. where
  572. d = leafdepth t
  573. d' = leafdepth t'
  574. ```
  575.  
  576. ####Cea mai indepartata frunza din arbore
  577.  
  578. ```haskell
  579. deepest2 :: Tree -> [Int]
  580. deepest2 Empty = []
  581. deepest2 (Leaf x) = [x]
  582. deepest2 (Node t t') | d > d' = deepest2 t
  583. | d < d' = deepest2 t'
  584. | otherwise = deepest2 t ++ deepest2 t'
  585. where
  586. d = leafdepth t
  587. d' = leafdepth t'
  588. ```
  589.  
  590. ###Alte surse
  591.  
  592.  
  593. ####Propoziti
  594.  
  595. ```haskell
  596. data Prop = X
  597. | F
  598. | T
  599. | Not Prop
  600. | Prop :|: Prop
  601. ```
  602.  
  603. #####Aproximarea expresiei
  604.  
  605. ```haskell
  606. showProp :: Prop -> String
  607. showProp X = "X"
  608. showProp F = "F"
  609. showProp T = "T"
  610. showProp (Not p) = "(~" ++ showProp p ++ ")"
  611. showProp (p :|: q) = "(" ++ showProp p ++ "|" ++ showProp q ++ ")"
  612. ```
  613.  
  614. #####Evaluarea expresiei
  615.  
  616. ```haskell
  617. eval :: Prop -> Bool -> Bool
  618. eval X v = v
  619. eval F _ = False
  620. eval T _ = True
  621. eval (Not p) v = not (eval p v)
  622. eval (p :|: q) v = (eval p v) || (eval q v)
  623. ```
  624.  
  625. #####Simplificarea expresiei
  626.  
  627. ```haskell
  628. simplify :: Prop -> Prop
  629. simplify X = X
  630. simplify F = F
  631. simplify T = T
  632. simplify (Not p) = negate (simplify p)
  633. where
  634. negate T = F
  635. negate F = T
  636. negate (Not p) = p
  637. negate p = Not p
  638. simplify (p :|: q) = disjoin (simplify p) (simplify q)
  639. where
  640. disjoin T p = T
  641. disjoin F p = p
  642. disjoin p T = T
  643. disjoin p F = p
  644. disjoin p q | p == q = p
  645. | otherwise = p :|: q
  646.  
  647.  
  648. ####Expresii
  649.  
  650. ```haskell
  651. data Expr = Var String
  652. | Expr :+: Expr
  653. | Expr :*: Expr
  654. ```
  655.  
  656. #####Este Norm daca expresia este suma
  657.  
  658. ```haskell
  659. isNorm :: Expr -> Bool
  660. isNorm (a:+:b) = isNorm a && isNorm b
  661. isNorm a = isTerm a
  662. ```
  663.  
  664. #####Este Term daca expresia este constanta sau produs
  665.  
  666. ```haskell
  667. isTerm :: Expr -> Bool
  668. isTerm (Var x) = True
  669. isTerm (a :+: b) = False
  670. isTerm (a :*: b) = isTerm a && isTerm b
  671. ```
  672.  
  673. #####Este normala daca expresia are proprietatea de distributivitate
  674.  
  675. ```haskell
  676. norm :: Expr -> Expr
  677. norm (Var v) = Var v
  678. norm (a :+: b) = norm a :+: norm b
  679. norm (a :*: b) = norm a *** norm b
  680. where
  681. (a :+: b) *** c = (a *** c) :+: (b *** c)
  682. a *** (b :+: c) = ( a *** b) :+: (a *** c)
  683. a *** b = a :*: b
  684. ```
  685.  
  686. ####Alte expresii
  687.  
  688. ```haskell
  689. data Expr = X
  690. | Const Int
  691. | Neg Expr
  692. | Expr :+: Expr
  693. | Expr :*: Expr
  694. ```
  695.  
  696. #####Transforma expresia intr-o aproximare matematica
  697.  
  698. ```haskell
  699. showExpr :: Expr -> String
  700. showExpr X = "X"
  701. showExpr (Const n) = show n
  702. showExpr (Neg p) = "(-" ++ showExpr p ++ ")"
  703. showExpr (p :+: q) = "(" ++ showExpr p ++ "+" ++ showExpr q ++ ")"
  704. showExpr (p :*: q) = "(" ++ showExpr p ++ "*" ++ showExpr q ++ ")"
  705. ```
  706.  
  707. #####Evalueaza expresia dupa un X dat
  708.  
  709. ```haskell
  710. evalExpr :: Expr -> Int -> Int
  711. evalExpr X v = v
  712. evalExpr (Const n) _ = n
  713. evalExpr (Neg p) v = - (evalExpr p v)
  714. evalExpr (p :+: q) v = (evalExpr p v) + (evalExpr q v)
  715. evalExpr (p :*: q) v = (evalExpr p v) * (evalExpr q v)
  716. ```
  717.  
  718. #####Transforma expresia in Scriere Poloneza Inversa
  719.  
  720. ```haskell
  721. rpn :: Expr -> [String]
  722. rpn X = ["X"]
  723. rpn (Const n) = [show n]
  724. rpn (Neg p) = rpn p ++ ["-"]
  725. rpn (p :+: q) = rpn p ++ rpn q ++ ["+"]
  726. rpn (p :*: q) = rpn p ++ rpn q ++ ["*"]
  727. ```
  728. #####Evalueaza o expresie in Scriere Poloneza Inversa
  729.  
  730. ```haskell
  731. evalrpn :: [String] -> Int -> Int
  732. evalrpn s n = the (foldl step [] s)
  733. where
  734. step (x:y:ys) "+" = (y + x):ys
  735. step (x:y:ys) "*" = (y * x):ys
  736. step (x:ys) "-" = (-x):ys
  737. step ys "X" = n:ys
  738. step ys m | all (\c -> isDigit c || c == '-') m = (read m :: Int):ys
  739. | otherwise = error "ill-formed RPN"
  740.  
  741. the :: [a] -> a
  742. the [x] = x
  743. the xs = error "ill-formed RPN"
  744. ```
  745.  
  746. ####Vectori
  747.  
  748. ```haskell
  749. data Term = Vec Scalar Scalar
  750. | Add Term Term
  751. | Mul Scalar Term
  752. ```
  753.  
  754. #####Evaluarea expresiei
  755.  
  756. ```haskell
  757. eva :: Term -> Vector
  758. eva (Vec x y) = (x,y)
  759. eva (Add t u) = add (eva t) (eva u)
  760. eva (Mul x t) = mul x (eva t)
  761. ```
  762.  
  763. #####Printare expresia ca pereche vector
  764.  
  765. ```haskell
  766. sho :: Term -> String
  767. sho (Vec x y) = show (x,y)
  768. sho (Add t u) = "(" ++ sho t ++ "+" ++ sho u ++ ")"
  769. sho (Mul x t) = "(" ++ show x ++ "*" ++ sho t ++ ")"
  770. ```
  771.  
  772. ####Puncte
  773.  
  774. ```haskell
  775. type Point = (Int,Int)
  776. data Points = Rectangle Point Point
  777. | Union Points Points
  778. | Difference Points Points
  779. ```
  780.  
  781. #####Verificare daca un punct este intre 2 puncte
  782.  
  783. ```haskell
  784. inPoints :: Point -> Points -> Bool
  785. inPoints (x,y) (Rectangle (left,top) (right,bottom)) = left <= x && x <= right && top <= y && y <= bottom
  786. inPoints p (Union ps qs) = inPoints p ps || inPoints p qs
  787. inPoints p (Difference ps qs) = inPoints p ps && not (inPoints p qs)
  788. ```
  789.  
  790. #####Desenare puncte
  791.  
  792. ```haskell
  793. showPoints :: Point -> Points -> [String]
  794. showPoints (a,b) ps = [ makeline y | y <- [0..b] ]
  795. where
  796. makeline y = [ if inPoints (x,y) ps then ’*’ else ’ ’ | x <- [0..a] ]
  797. ```
  798.  
  799. ---
  800.  
  801. #Monads
  802.  
  803. ```haskell
  804. class Monad m where
  805. return :: a -> m a
  806. (>>=) :: m a -> (a -> m b) -> m b
  807. ```
  808.  
  809. unde:
  810.  
  811. - `m` este un constructor de tipuri
  812. `m a` — tipul computatiilor care produc rezultate de tip a
  813. - tipul `a -> m b` este tipul continuarilor
  814. Continuare: O functie care foloses,te un rezultat de tip `a` pentru a produce o computatie de tip `b`
  815. - `(>>=)` este operatia de „secventiere” a computatiilor
  816. - `return` este continuarea triviala
  817. Pentru un `v` dat, produce computatia care va avea ca rezultat acel `v`.
  818.  
  819. Deci un monad in cod arata cam asa:
  820.  
  821. ```haskell
  822. instance Monad Parser where
  823. return x = Parser (\s -> [(x,s)])
  824. m >>= k = Parser (\s -> [(y,u)|
  825. (x, t) <− apply m s,
  826. (y, u) <− apply (k x) t ])
  827. ```
  828.  
  829. ##Monadul maybe
  830.  
  831. ```
  832. instance Monad Maybe where
  833. Just x >>= k = k x
  834. Nothing >>= k = Nothing
  835. return x = Just x
  836. ```
  837.  
  838. ##MyIO
  839.  
  840. ```haskell
  841. -- How the IO monad works
  842.  
  843. module MyIO(MyIO, myPutChar, myGetChar, convert) where
  844.  
  845. type Input = String
  846. type Remainder = String
  847. type Output = String
  848.  
  849. data MyIO a = MyIO (Input -> (a, Remainder, Output))
  850.  
  851. apply :: MyIO a -> Input -> (a, Remainder, Output)
  852. apply (MyIO f) inp = f inp
  853.  
  854. myPutChar :: Char -> MyIO ()
  855. myPutChar ch = MyIO (\inp -> ((), inp, [ch]))
  856.  
  857. myGetChar :: MyIO Char
  858. myGetChar = MyIO (\(ch:rem) -> (ch, rem, []))
  859.  
  860. instance Monad MyIO where
  861. return x = MyIO (\inp -> (x, inp, ""))
  862. m >>= k = MyIO (\inp ->
  863. let (x, rem1, out1) = apply m inp in
  864. let (y, rem2, out2) = apply (k x) rem1 in
  865. (y, rem2, out1++out2))
  866.  
  867. convert :: MyIO () -> IO ()
  868. convert m = interact (\inp ->
  869. let (x, rem, out) = apply m inp in
  870. out)
  871.  
  872. ```
  873.  
  874. ##Parser
  875.  
  876. ```haskell
  877. module Parser(Parser,apply,parse,char,spot,
  878. token,star,plus,parseInt) where
  879.  
  880. import Data.Char
  881. import Control.Monad
  882.  
  883. -- The type of parsers
  884. newtype Parser a = Parser (String -> [(a, String)])
  885.  
  886. -- Apply a parser
  887. apply :: Parser a -> String -> [(a, String)]
  888. apply (Parser f) s = f s
  889.  
  890. -- Return parsed value, assuming at least one successful parse
  891. parse :: Parser a -> String -> a
  892. parse m s = one [ x | (x,t) <- apply m s, t == "" ]
  893. where
  894. one [] = error "no parse"
  895. one [x] = x
  896. one xs | length xs > 1 = error "ambiguous parse"
  897.  
  898. -- Parsers form a monad
  899.  
  900. -- class Monad m where
  901. -- return :: a -> m a
  902. -- (>>=) :: m a -> (a -> m b) -> m b
  903.  
  904. instance Monad Parser where
  905. return x = Parser (\s -> [(x,s)])
  906. m >>= k = Parser (\s ->
  907. [ (y, u) |
  908. (x, t) <- apply m s,
  909. (y, u) <- apply (k x) t ])
  910.  
  911. -- Parsers form a monad with sums
  912.  
  913. -- class MonadPlus m where
  914. -- mzero :: m a
  915. -- mplus :: m a -> m a -> m a
  916.  
  917. instance MonadPlus Parser where
  918. mzero = Parser (\s -> [])
  919. mplus m n = Parser (\s -> apply m s ++ apply n s)
  920.  
  921. -- Parse one character
  922. char :: Parser Char
  923. char = Parser f
  924. where
  925. f [] = []
  926. f (c:s) = [(c,s)]
  927.  
  928. -- guard :: MonadPlus m => Bool -> m ()
  929. -- guard False = mzero
  930. -- guard True = return ()
  931.  
  932. -- Parse a character satisfying a predicate (e.g., isDigit)
  933. spot :: (Char -> Bool) -> Parser Char
  934. spot p = do { c <- char; guard (p c); return c }
  935.  
  936. -- Match a given character
  937. token :: Char -> Parser Char
  938. token c = spot (== c)
  939.  
  940. -- Perform a list of commands, returning a list of values
  941. -- sequence :: Monad m => [m a] -> m [a]
  942. -- sequence []
  943. -- sequence (m:ms) = do {
  944. -- x <- m;
  945. -- xs <- sequence ms;
  946. -- return (x:xs)
  947. -- }
  948.  
  949. -- match a given string (defined two ways)
  950. match :: String -> Parser String
  951. match [] = return []
  952. match (x:xs) = do {
  953. y <- token x;
  954. ys <- match xs;
  955. return (y:ys)
  956. }
  957.  
  958. match' :: String -> Parser String
  959. match' xs = sequence (map token xs)
  960.  
  961. -- match zero or more occurrences
  962. star :: Parser a -> Parser [a]
  963. star p = plus p `mplus` return []
  964.  
  965. -- match one or more occurrences
  966. plus :: Parser a -> Parser [a]
  967. plus p = do x <- p
  968. xs <- star p
  969. return (x:xs)
  970.  
  971. -- match a natural number
  972. parseNat :: Parser Int
  973. parseNat = do s <- plus (spot isDigit)
  974. return (read s)
  975.  
  976. -- match a negative number
  977. parseNeg :: Parser Int
  978. parseNeg = do token '-'
  979. n <- parseNat
  980. return (-n)
  981.  
  982. -- match an integer
  983. parseInt :: Parser Int
  984. parseInt = parseNat `mplus` parseNeg
  985.  
  986. ```
  987.  
  988. ###Parser folosit in evaluare de expresii
  989.  
  990. ```haskell
  991. module Exp where
  992.  
  993. import Control.Monad
  994. import Parser
  995.  
  996. data Exp = Lit Int
  997. | Exp :+: Exp
  998. | Exp :*: Exp
  999. deriving (Eq,Show)
  1000.  
  1001. evalExp :: Exp -> Int
  1002. evalExp (Lit n) = n
  1003. evalExp (e :+: f) = evalExp e + evalExp f
  1004. evalExp (e :*: f) = evalExp e * evalExp f
  1005.  
  1006. parseExp :: Parser Exp
  1007. parseExp = parseLit `mplus` parseAdd `mplus` parseMul
  1008. where
  1009. parseLit = do { n <- parseInt;
  1010. return (Lit n) }
  1011. parseAdd = do { token '(';
  1012. d <- parseExp;
  1013. token '+';
  1014. e <- parseExp;
  1015. token ')';
  1016. return (d :+: e) }
  1017. parseMul = do { token '(';
  1018. d <- parseExp;
  1019. token '*';
  1020. e <- parseExp;
  1021. token ')';
  1022. return (d :*: e) }
  1023.  
  1024. test :: Bool
  1025. test =
  1026. parse parseExp "(1+(2*3))" == (Lit 1 :+: (Lit 2 :*: Lit 3)) &&
  1027. parse parseExp "((1+2)*3)" == ((Lit 1 :+: Lit 2) :*: Lit 3)
  1028. ```
  1029.  
  1030.  
  1031.  
  1032.  
  1033.  
  1034.  
  1035.  
  1036.  
  1037.  
  1038.  
  1039.  
  1040. LAB1
  1041.  
  1042. import Data.List
  1043.  
  1044. myInt = 5555555555555555555555555555555555555555555555555555555555555555555555555555555555555
  1045.  
  1046. double :: Integer -> Integer
  1047. double x = x+x
  1048.  
  1049. triple :: Integer -> Integer
  1050. triple x = x+x+x
  1051.  
  1052.  
  1053. maxim :: Integer -> Integer -> Integer
  1054. maxim x y =
  1055. if (x > y)
  1056. then x
  1057. else y
  1058.  
  1059. maxim3 :: Integer -> Integer -> Integer -> Integer
  1060. maxim3 x y z =
  1061. if (x > y)
  1062. then
  1063. if (x > z)
  1064. then x
  1065. else z
  1066. else
  1067. if (y > z)
  1068. then y
  1069. else z
  1070.  
  1071. max3 :: Integer -> Integer -> Integer -> Integer
  1072. max3 x y z =
  1073. let
  1074. u = maxim x y
  1075. in
  1076. maxim u z
  1077.  
  1078. maxim4 :: Integer -> Integer -> Integer -> Integer -> Integer
  1079. maxim4 x y z w =
  1080. let
  1081. u = maxim x y
  1082. in
  1083. let
  1084. v = maxim z w
  1085. in
  1086. maxim u v
  1087.  
  1088. testmaxim4 :: Integer -> Integer -> Integer -> Integer -> Bool
  1089. testmaxim4 x y z w =
  1090. let
  1091. r = maxim4 x y z w
  1092. in
  1093. if (r >= x && r >= y && r >= z && r >=w)
  1094. then True
  1095. else False
  1096.  
  1097.  
  1098. LAB2
  1099.  
  1100.  
  1101. -- la nevoie decomentati liniile urmatoare:
  1102.  
  1103. import Data.Char
  1104. import Data.List
  1105.  
  1106.  
  1107. ---------------------------------------------
  1108. -------RECURSIE: FIBONACCI-------------------
  1109. ---------------------------------------------
  1110.  
  1111. fibonacciCazuri :: Integer -> Integer
  1112. fibonacciCazuri n
  1113. | n < 2 = n
  1114. | otherwise = fibonacciCazuri (n - 1) + fibonacciCazuri (n - 2)
  1115.  
  1116. fibonacciEcuational :: Integer -> Integer
  1117. fibonacciEcuational 0 = 0
  1118. fibonacciEcuational 1 = 1
  1119. fibonacciEcuational n =
  1120. fibonacciEcuational (n - 1) + fibonacciEcuational (n - 2)
  1121.  
  1122. fibonacciLiniar :: Integer -> Integer
  1123. fibonacciLiniar 0 = 0
  1124. fibonacciLiniar n = snd (fibonacciPereche n)
  1125. where
  1126. fibonacciPereche :: Integer -> (Integer, Integer)
  1127. fibonacciPereche 1 = (0, 1)
  1128. fibonacciPereche n =
  1129. let
  1130. pereche = fibonacciPereche(n - 1)
  1131. in
  1132. (snd(pereche), fst(pereche) + snd(pereche))
  1133.  
  1134.  
  1135.  
  1136. ---------------------------------------------
  1137. ----------RECURSIE PE LISTE -----------------
  1138. ---------------------------------------------
  1139. semiPareRecDestr :: [Int] -> [Int]
  1140. semiPareRecDestr l
  1141. | null l = l
  1142. | even h = h `div` 2 : t'
  1143. | otherwise = t'
  1144. where
  1145. h = head l
  1146. t = tail l
  1147. t' = semiPareRecDestr t
  1148.  
  1149. semiPareRecEq :: [Int] -> [Int]
  1150. semiPareRecEq [] = []
  1151. semiPareRecEq (h:t)
  1152. | even h = h `div` 2 : t'
  1153. | otherwise = t'
  1154. where t' = semiPareRecEq t
  1155.  
  1156. ---------------------------------------------
  1157. ----------DESCRIERI DE LISTE ----------------
  1158. ---------------------------------------------
  1159. semiPareComp :: [Int] -> [Int]
  1160. semiPareComp l = [ x `div` 2 | x <- l, even x ]
  1161.  
  1162.  
  1163. -- L2.2
  1164. inIntervalRec :: Int -> Int -> [Int] -> [Int]
  1165. inIntervalRec lo hi [] = []
  1166. inIntervalRec lo hi (x:xs)
  1167. | lo <= x && x <= hi = x : xs'
  1168. | otherwise = xs'
  1169. where xs' = inIntervalRec lo hi xs
  1170.  
  1171. inIntervalComp :: Int -> Int -> [Int] -> [Int]
  1172. inIntervalComp lo hi xs = [ x | x <- xs, lo <= x && x <= hi ]
  1173.  
  1174. -- L2.3
  1175.  
  1176. pozitiveRec :: [Int] -> Int
  1177. pozitiveRec [] = 0
  1178. pozitiveRec (h:t) =
  1179. if (h > 0) then 1 + pozitiveRec t
  1180. else pozitiveRec t
  1181.  
  1182.  
  1183. pozitiveComp :: [Int] -> Int
  1184. pozitiveComp l = sum [ 1 | x <- l, x > 0]
  1185.  
  1186. -- L2.4
  1187. pozitiiImpareRec :: [Int] -> Int -> [Int]
  1188. pozitiiImpareRec [] _ = []
  1189. pozitiiImpareRec (h:t) poz
  1190. | odd h = poz : pozitiiImpareRec t (poz + 1)
  1191. | otherwise = pozitiiImpareRec t (poz + 1)
  1192.  
  1193. pozitiiImpareComp :: [Int] -> [Int]
  1194. pozitiiImpareComp l = [i | (x, i) <- zip l [0..], odd x]
  1195.  
  1196.  
  1197. -- L2.5
  1198.  
  1199. multDigitsRec :: String -> Int
  1200. multDigitsRec [] = 1
  1201. multDigitsRec (h:t) =
  1202. if (isDigit h) then digitToInt h * multDigitsRec t
  1203. else multDigitsRec t
  1204.  
  1205. multDigitsComp :: String -> Int
  1206. multDigitsComp sir = product [digitToInt x | x <- sir, isDigit x]
  1207.  
  1208. -- L2.6
  1209.  
  1210. discountRec :: [Float] -> [Float]
  1211. discountRec [] = []
  1212. discountRec (h:t)
  1213. | h - h * 0.25 < 200 = h - h * 0.25 : discountRec t
  1214. | otherwise = discountRec t
  1215.  
  1216. discountComp :: [Float] -> [Float]
  1217. discountComp list = [h - h * 0.25 | h <- list, h - h * 0.25 < 200]
  1218.  
  1219.  
  1220. LAB3
  1221.  
  1222. import Data.List
  1223.  
  1224. -- L3.1 Încercati sa gasiti valoarea expresiilor de mai jos si
  1225. -- verificati raspunsul gasit de voi în interpretor:
  1226. {-
  1227. [x^2 | x <- [1 .. 10], x `rem` 3 == 2]
  1228. [(x, y) | x <- [1 .. 5], y <- [x .. (x+2)]]
  1229. [(x, y) | x <- [1 .. 3], let k = x^2, y <- [1 .. k]]
  1230. [x | x <- "Facultatea de Matematica si Informatica", elem x ['A' .. 'Z']]
  1231. [[x .. y] | x <- [1 .. 5], y <- [1 .. 5], x < y ]
  1232.  
  1233. -}
  1234.  
  1235. factori :: Int -> [Int]
  1236. factori n = [x | x <- [1 .. n], n `rem` x == 0]
  1237.  
  1238. prim :: Int -> Bool
  1239. prim x =
  1240. let
  1241. u = factori x
  1242. in
  1243. if (length u == 2) then True
  1244. else False
  1245.  
  1246. numerePrime :: Int -> [Int]
  1247. numerePrime x = [nr | nr <- [2..x], prim nr]
  1248.  
  1249. -- L3.2 Testati si sesizati diferenta:
  1250. -- [(x,y) | x <- [1..5], y <- [1..3]]
  1251. -- zip [1..5] [1..3]
  1252.  
  1253. myzip3 :: [Int] -> [Int] -> [Int] -> [(Int, Int, Int)]
  1254. myzip3 l1 l2 l3 = [(a, b, c) | (a, (b, c)) <- zip l1 (zip l2 l3)]
  1255.  
  1256.  
  1257. --------------------------------------------------------
  1258. ----------FUNCTII DE NIVEL INALT -----------------------
  1259. --------------------------------------------------------
  1260. aplica2 :: (a -> a) -> a -> a
  1261. --aplica2 f x = f (f x)
  1262. --aplica2 f = f.f
  1263. --aplica2 f = \x -> f (f x)
  1264. aplica2 = \f x -> f (f x)
  1265.  
  1266. -- L3.3
  1267. {-
  1268.  
  1269. map (\ x -> 2 * x) [1 .. 10]
  1270. map (1 `elem` ) [[2, 3], [1, 2]]
  1271. map ( `elem` [2, 3] ) [1, 3, 4, 5]
  1272.  
  1273. -}
  1274.  
  1275. -- firstEl [ ('a', 3), ('b', 2), ('c', 1)]
  1276. firstEl l = map (\(a, b) -> a) l
  1277. -- firstEl l = map fst l
  1278.  
  1279. -- sumList [[1, 3],[2, 4, 5], [], [1, 3, 5, 6]]
  1280. sumList l = map (\x -> sum x) l
  1281. -- sumList l = map sum l
  1282.  
  1283. -- prel2 [2,4,5,6]
  1284. prel2 l = map (\x -> if (odd x) then 2 * x else x `div` 2) l
  1285.  
  1286. -- filter p xs = [ x | x <- xs , p x ]
  1287.  
  1288. filter1 :: Char -> [String] -> [String]
  1289. filter1 c l = filter (\x -> elem c x) l
  1290.  
  1291. filter2 :: [Int] -> [Int]
  1292. filter2 l = map (^2) (filter odd l)
  1293.  
  1294. filter3 :: [Int] -> [Int]
  1295. filter3 l = map (^2) [b | (a, b) <- zip [1..] l , odd a]
  1296.  
  1297. numaiVocale :: [String] -> [String]
  1298. numaiVocale l = map (filter (`elem` "aeiouAEIOU")) l
  1299.  
  1300. mymap f list = [f x | x <- list]
  1301. myfilter f list = [x | x<- list, f x]
  1302.  
  1303.  
  1304.  
  1305. LAB4
  1306.  
  1307.  
  1308. import Numeric.Natural
  1309.  
  1310. numerePrimeCiur :: Int -> [Int]
  1311. numerePrimeCiur n = numerePrimeCiurAux[2..n]
  1312.  
  1313. numerePrimeCiurAux [] = []
  1314. numerePrimeCiurAux (x : xs) = x : numerePrimeCiurAux(filter (\y -> mod y x /= 0) xs)
  1315.  
  1316. ordonataNat :: [Int] -> Bool
  1317. ordonataNat [] = True
  1318. ordonataNat [x] = True
  1319. ordonataNat (x:y:xs) = and [a <= b | (a, b) <- zip (x:xs) xs]
  1320.  
  1321.  
  1322. ordonataNat1 :: [Int] -> Bool
  1323. ordonataNat1 [] = True
  1324. ordonataNat1 [x] = True
  1325. ordonataNat1 (x:y:xs)
  1326. | x <= y = and([True] ++ [ordonataNat1 (y:xs)])
  1327. | otherwise = False
  1328. --ordonataNat1 (x:y:xs) = x <= y && ordonataNat1(y:xs)
  1329.  
  1330. ordonata :: [a] -> (a -> a -> Bool) -> Bool
  1331. ordonata [] _ = True
  1332. ordonata [x] _ = True
  1333. ordonata (x:y:xs) f = and [x `f` y, ordonata (y:xs) f]
  1334.  
  1335. (*<*) :: (Integer,Integer) -> (Integer,Integer) -> Bool
  1336. (a, b) *<* (c, d) = mod a 10 == 0 && mod c 10 == 0
  1337.  
  1338.  
  1339. compuneList :: (b -> c) -> [(a -> b)] -> [(a -> c)]
  1340. compuneList f gs = [f . g | g <- gs]
  1341.  
  1342. aplicaList :: a -> [(a -> b)] ->[b]
  1343. aplicaList x fs = [f x | f <- fs]
  1344.  
  1345. myzip3 :: [a] -> [b] -> [c] -> [(a,b,c)]
  1346. myzip3 x y z = map (\(a,(b,c)) -> (a,b,c)) (zip x (zip y z))
  1347.  
  1348.  
  1349.  
  1350. produsRec :: [Integer] -> Integer
  1351. produsRec [] = 1
  1352. produsRec (x:xs) = x * produsRec xs
  1353.  
  1354.  
  1355. produsFold :: [Integer] -> Integer
  1356. produsFold l = foldr (*) 1 l
  1357.  
  1358.  
  1359. andRec :: [Bool] -> Bool
  1360. andRec [] = True
  1361. andRec (x:xs) = x && andRec xs
  1362.  
  1363. andFold :: [Bool] -> Bool
  1364. andFold l = foldr (&&) True l
  1365.  
  1366. concatRec :: [[a]] -> [a]
  1367. concatRec [] = []
  1368. concatRec (x:xs) = x ++ concatRec xs
  1369.  
  1370.  
  1371. concatFold :: [[a]] -> [a]
  1372. concatFold l = foldr (++) [] l
  1373.  
  1374. rmChar :: Char -> String -> String
  1375. rmChar c str = filter (\cc -> cc /= c) str
  1376.  
  1377.  
  1378.  
  1379.  
  1380. rmCharsRec :: String -> String -> String
  1381. rmCharsRec [] str = str
  1382. rmCharsRec (x:xs) str = rmCharsRec xs (rmChar x str)
  1383.  
  1384. test_rmchars :: Bool
  1385. test_rmchars = rmCharsRec ['a'..'l'] "fotbal" == "ot"
  1386.  
  1387.  
  1388.  
  1389. rmCharsFold :: String -> String -> String
  1390. rmCharsFold str1 str2 = foldr rmChar str2 str1
  1391.  
  1392.  
  1393.  
  1394. logistic :: Num a => a -> a -> Natural -> a
  1395. logistic rate start = f
  1396. where
  1397. f 0 = start
  1398. f n = rate * f (n - 1) * (1 - f (n - 1))
  1399.  
  1400.  
  1401.  
  1402.  
  1403. logistic0 :: Fractional a => Natural -> a
  1404. logistic0 = logistic 3.741 0.00079
  1405. ex1 :: Natural
  1406. ex1 = 500
  1407.  
  1408.  
  1409. ex20 :: Fractional a => [a]
  1410. ex20 = [1, logistic0 ex1, 3]
  1411.  
  1412. ex21 :: Fractional a => a
  1413. ex21 = head ex20
  1414.  
  1415. ex22 :: Fractional a => a
  1416. ex22 = ex20 !! 2
  1417.  
  1418. ex23 :: Fractional a => [a]
  1419. ex23 = drop 2 ex20
  1420.  
  1421. ex24 :: Fractional a => [a]
  1422. ex24 = tail ex20
  1423.  
  1424.  
  1425. ex31 :: Natural -> Bool
  1426. ex31 x = x < 7 || logistic0 (ex1 + x) > 2
  1427.  
  1428. ex32 :: Natural -> Bool
  1429. ex32 x = logistic0 (ex1 + x) > 2 || x < 7
  1430. ex33 :: Bool
  1431. ex33 = ex31 5
  1432.  
  1433. ex34 :: Bool
  1434. ex34 = ex31 7
  1435.  
  1436. ex35 :: Bool
  1437. ex35 = ex32 5
  1438.  
  1439. ex36 :: Bool
  1440. ex36 = ex32 7
  1441. findFirst :: (a -> Bool) -> [a] -> Maybe a
  1442. findFirst p [] = Nothing
  1443. findFirst p (x:xs) = if (p x) then Just x else (findFirst p xs)
  1444. findFirstNat :: (Natural -> Bool) -> Natural
  1445. findFirstNat p = n
  1446. where Just n = findFirst p [0..]
  1447.  
  1448.  
  1449.  
  1450. ex4b :: Natural
  1451. ex4b = findFirstNat (\n -> n * n >= 12347)
  1452. inversa :: Ord a => (Natural -> a) -> (a -> Natural)
  1453. inversa = undefined
  1454.  
  1455.  
  1456. LAB5
  1457.  
  1458. -- http://www.inf.ed.ac.uk/teaching/courses/inf1/fp/
  1459.  
  1460.  
  1461.  
  1462. import Data.Char
  1463. import Data.List
  1464.  
  1465.  
  1466. -- 1.
  1467. rotate :: Int -> [Char] -> [Char]
  1468. rotate 0 list = list
  1469. rotate n (x:xs) = rotate (n-1) (xs ++ [x])
  1470.  
  1471. -- 2.
  1472. prop_rotate :: Int -> String -> Bool
  1473. prop_rotate k str = rotate (l - m) (rotate m str) == str
  1474. where l = length str
  1475. m = if l == 0 then 0 else k `mod` l
  1476.  
  1477. -- 3.
  1478. makeKey :: Int -> [(Char, Char)]
  1479. makeKey k = zip ['A'..'Z'] (rotate k ['A'..'Z'])
  1480.  
  1481. -- 4.
  1482. lookUp :: Char -> [(Char, Char)] -> Char
  1483. lookUp c [] = c
  1484. lookUp c ((key, value):lista) = if (c==key) then value else lookUp c lista
  1485.  
  1486. -- 5.
  1487. encipher :: Int -> Char -> Char
  1488. encipher k ch = lookUp ch (makeKey k)
  1489.  
  1490. -- 6.
  1491. normalize :: String -> String
  1492. normalize [] = []
  1493. normalize (x:xs)
  1494. | isLower x || isUpper x = [toUpper x] ++ normalize xs
  1495. | isDigit x = [x] ++ normalize xs
  1496. | otherwise = normalize xs
  1497.  
  1498. -- 7.
  1499. encipherStr :: Int -> String -> String
  1500. encipherStr k str = [encipher k ch | ch <- normalize str]
  1501.  
  1502. -- 8.
  1503. reverseKey :: [(Char, Char)] -> [(Char, Char)]
  1504. reverseKey list = [(b, a) | (a, b) <- list]
  1505.  
  1506. -- 9.
  1507. decipher :: Int -> Char -> Char
  1508. decipher k ch = lookUp ch (reverseKey (makeKey k))
  1509.  
  1510. decipherStr :: Int -> String -> String
  1511. decipherStr n str = [decipher n ch | ch <- normalize str]
  1512.  
  1513. -- 11.
  1514. contains :: String -> String -> Bool
  1515. contains [] _ = False
  1516. contains (x:xs) small = if isPrefixOf small (x:xs) then True else contains xs small
  1517.  
  1518. contains_the_and :: String -> Bool
  1519. contains_the_and str = contains str "THE" || contains str "AND"
  1520.  
  1521. -- 12.
  1522. candidates :: String -> [(Int, String)]
  1523. candidates str = [(n, decipherStr n str) | n <- [0..25], contains_the_and (decipherStr n str)]
  1524.  
  1525. LAB6
  1526.  
  1527. import Data.Char
  1528. import Data.List
  1529.  
  1530. prelStr strin = map toUpper strin
  1531. ioString = do
  1532. strin <- getLine
  1533. putStrLn $ "Intrare\n" ++ strin
  1534. let strout = prelStr strin
  1535. putStrLn $ "Iesire\n" ++ strout
  1536.  
  1537.  
  1538. prelNo noin = sqrt noin
  1539. ioNumber = do
  1540. noin <- readLn :: IO Double
  1541. putStrLn $ "Intrare\n" ++ (show noin)
  1542. let noout = prelNo noin
  1543. putStrLn $ "Iesire"
  1544. print noout
  1545.  
  1546. inoutFile = do
  1547. sin <- readFile "Input.txt"
  1548. putStrLn $ "Intrare\n" ++ sin
  1549. let sout = prelStr sin
  1550. putStrLn $ "Iesire\n" ++ sout
  1551. writeFile "Output.txt" sout
  1552.  
  1553.  
  1554. prelStr2 :: String -> String
  1555. prelStr2 [] = []
  1556. prelStr2 [x] = [toUpper x]
  1557. prelStr2 (x1:x2:xs) = [toUpper x1, toLower x2] ++ prelStr2(xs)
  1558.  
  1559. ioString2 = do
  1560. strin <- getLine
  1561. putStrLn $ "Intrare\n" ++ strin
  1562. let strout = prelStr2 strin
  1563. putStrLn $ "Iesire\n" ++ strout
  1564.  
  1565.  
  1566.  
  1567. citirePersoane 0 (varstaMax, numeMax) = print ("Persoana " ++ numeMax ++ " are varsta: " ++ show(varstaMax))
  1568. citirePersoane n (varstaMax, numeMax) = do
  1569. nume <- getLine
  1570. varsta <- readLn :: IO Int
  1571. citirePersoane (n - 1) (if varstaMax < varsta then (varsta, nume) else (varstaMax, numeMax))
  1572. persoane = do
  1573. n <- readLn :: IO Int
  1574. citirePersoane n (0, "")
  1575.  
  1576.  
  1577. mySplit :: String -> Char -> String -> [String]
  1578. mySplit [] _ buf = [buf]
  1579. mySplit (x:xs) c buffer = if x == c then buffer:(mySplit xs c "") else mySplit xs c (buffer ++ [x])
  1580.  
  1581. auxEx2 :: [(String, Int)] -> (String, Int) -> String
  1582. auxEx2 [] (numeMax, varstaMax) = ("Persoana " ++ numeMax ++ " are varsta: " ++ show(varstaMax))
  1583. auxEx2 ((nume, varsta):xs) (numeMax, varstaMax) = auxEx2 xs (if varstaMax < varsta then (nume, varsta) else (numeMax, varstaMax))
  1584.  
  1585. ex2 = do
  1586. continutFisier <- readFile "ex2.in"
  1587. print continutFisier
  1588. let listaPersoane = init (mySplit continutFisier '\n' "")
  1589. print listaPersoane
  1590. let listaPerechi = map (\x -> mySplit x ',' "") listaPersoane
  1591. print listaPerechi
  1592. let listaPerechiBune = map (\[nume, varsta] -> (nume, read varsta :: Int)) listaPerechi
  1593. print listaPerechiBune
  1594. print(auxEx2 listaPerechiBune ("",0))
  1595.  
  1596.  
  1597. LAB7
  1598.  
  1599. import Data.List (nub)
  1600. import Data.Maybe (fromJust)
  1601.  
  1602. data Fruct
  1603. = Mar String Bool
  1604. | Portocala String Int
  1605. deriving(Show)
  1606.  
  1607.  
  1608. ionatanFaraVierme = Mar "Ionatan" False
  1609. goldenCuVierme = Mar "Golden Delicious" True
  1610. portocalaSicilia10 = Portocala "Sanguinello" 10
  1611. listaFructe = [Mar "Ionatan" False, Portocala "Sanguinello" 10, Portocala "Valencia" 22, Mar "Golden Delicious" True, Portocala "Sanguinello" 15, Portocala "Moro" 12, Portocala "Tarocco" 3, Portocala "Moro" 12, Portocala "Valencia" 2, Mar "Golden Delicious" False, Mar "Golden" False, Mar "Golden" True]
  1612.  
  1613.  
  1614. ePortocalaDeSicilia :: Fruct -> Bool
  1615. ePortocalaDeSicilia (Mar _ _) = False
  1616. ePortocalaDeSicilia (Portocala tip _) = tip `elem` ["Tarocco", "Moro", "Sanguinello"]
  1617.  
  1618. test_ePortocalaDeSicilia1 = ePortocalaDeSicilia (Portocala "Moro" 12) == True
  1619. test_ePortocalaDeSicilia2 = ePortocalaDeSicilia (Mar "Ionatan" True) == False
  1620.  
  1621. nrFeliiSicilia :: [Fruct] -> Int
  1622. nrFeliiSicilia [] = 0
  1623. nrFeliiSicilia (Mar _ _ : xs) = nrFeliiSicilia xs
  1624. nrFeliiSicilia (Portocala tip nr : xs) = if (tip `elem` ["Tarocco", "Moro", "Sanguinello"]) then nr + nrFeliiSicilia xs else nrFeliiSicilia xs
  1625. --nrFeliiSicilia lista = sum [nrFelii | Portocala tip nrFelii <- filter ePortocalaDeSicilia listaFructe]
  1626.  
  1627. test_nrFeliiSicilia = nrFeliiSicilia listaFructe == 52
  1628.  
  1629. nrMereViermi :: [Fruct] -> Int
  1630. nrMereViermi [] = 0
  1631. nrMereViermi (Mar _ viermi : xs) = if (viermi) then 1 + nrMereViermi xs else nrMereViermi xs
  1632. nrMereViermi (Portocala _ _ : xs) = nrMereViermi xs
  1633.  
  1634. test_nrMereViermi = nrMereViermi listaFructe == 2
  1635.  
  1636. type NumeA = String
  1637. type Rasa = String
  1638. data Animal = Pisica NumeA | Caine NumeA Rasa
  1639.  
  1640. vorbeste :: Animal -> String
  1641. vorbeste (Pisica _ ) = "Meow!"
  1642. vorbeste (Caine _ _) = "Woof!"
  1643.  
  1644. rasa :: Animal -> Maybe String
  1645. rasa (Pisica _ ) = Nothing
  1646. rasa (Caine _ rasa) = Just rasa
  1647.  
  1648. type Nume = String
  1649. data Prop
  1650. = Var Nume
  1651. | F
  1652. | T
  1653. | Not Prop
  1654. | Prop :|: Prop
  1655. | Prop :&: Prop
  1656. deriving (Eq, Read)
  1657. infixr 2 :|:
  1658. infixr 3 :&:
  1659.  
  1660. p1 :: Prop
  1661. p1 = (Var "P" :|: Var "Q") :&: (Var "P" :&: Var "Q")
  1662.  
  1663. p2 :: Prop
  1664. p2 = undefined
  1665.  
  1666. p3 :: Prop
  1667. p3 = undefined
  1668.  
  1669. instance Show Prop where
  1670. show F = "F"
  1671. show T = "T"
  1672. show (Var v) = v
  1673. show (Not p) = "(~" ++ show p ++ ")"
  1674. show(p :|: q) = "(" ++ show p ++ "|" ++ show q ++ ")"
  1675. show(p :&: q) = "(" ++ show p ++ "&" ++ show q ++ ")"
  1676.  
  1677. test_ShowProp :: Bool
  1678. test_ShowProp = show (Not (Var "P") :&: Var "Q") == "((~P)&Q)"
  1679.  
  1680. type Env = [(Nume, Bool)]
  1681.  
  1682. impureLookup :: Eq a => a -> [(a,b)] -> b
  1683. impureLookup a = fromJust . lookup a
  1684.  
  1685. eval :: Prop -> Env -> Bool
  1686. eval F _ = False
  1687. eval T _ = True
  1688. eval (Var v) env = impureLookup v env
  1689. eval (Not p) env = not (eval p env)
  1690. eval (p :|: q) env = eval p env || eval q env
  1691. eval (p :&: q) env = eval p env && eval q env
  1692.  
  1693. test_eval = eval (Var "P" :|: Var "Q") [("P", True), ("Q", False)] == True
  1694.  
  1695.  
  1696. variabile :: Prop -> [Nume]
  1697. variabile F = []
  1698. variabile T = []
  1699. variabile (Var v) = [v]
  1700. variabile (Not p) = nub (variabile p)
  1701. variabile (p :|: q) = nub (variabile p ++ variabile q)
  1702. variabile (p :&: q) = nub (variabile p ++ variabile q)
  1703.  
  1704. test_variabile = variabile (Not (Var "P") :&: Var "Q") == ["P", "Q"]
  1705.  
  1706. envs :: [Nume] -> [Env]
  1707. envs [x] = [[(x, False)], [(x, True)]]
  1708. envs (x:xs) = [(x, False):lista | lista <- envs xs] ++ [(x, True):lista | lista <- envs xs]
  1709.  
  1710. test_envs =
  1711. envs ["P", "Q"]
  1712. ==
  1713. [ [ ("P",False)
  1714. , ("Q",False)
  1715. ]
  1716. , [ ("P",False)
  1717. , ("Q",True)
  1718. ]
  1719. , [ ("P",True)
  1720. , ("Q",False)
  1721. ]
  1722. , [ ("P",True)
  1723. , ("Q",True)
  1724. ]
  1725. ]
  1726.  
  1727. satisfiabila :: Prop -> Bool
  1728. satisfiabila p = or [eval p env| env <- envs $ variabile p]
  1729.  
  1730. test_satisfiabila1 = satisfiabila (Not (Var "P") :&: Var "Q") == True
  1731. test_satisfiabila2 = satisfiabila (Not (Var "P") :&: Var "P") == False
  1732.  
  1733. valida :: Prop -> Bool
  1734. --valida p = and [eval p env| env <- envs $ variabile p]
  1735. valida p = satisfiabila (Not p) == False
  1736.  
  1737. test_valida1 = valida (Not (Var "P") :&: Var "Q") == False
  1738. test_valida2 = valida (Not (Var "P") :|: Var "P") == True
  1739.  
  1740. auxHead :: Prop -> String
  1741. auxHead p = concat (variabile p) ++ "|" ++ show p
  1742.  
  1743. auxBody :: Prop -> [Env] -> IO()
  1744. auxBody p [] = print ""
  1745. auxBody p (env:envs) = do
  1746. putStrLn $ (map (\(_, b) -> bool2String b) env) ++ "|" ++ [(bool2String (eval p env))]
  1747. auxBody p envs
  1748.  
  1749. bool2String :: Bool -> Char
  1750. bool2String False = 'F'
  1751. bool2String True = 'T'
  1752.  
  1753. tabelaAdevar :: Prop -> IO ()
  1754. tabelaAdevar p = do
  1755. putStrLn (auxHead p)
  1756. putStrLn $ "---------------"
  1757. auxBody p (envs $ variabile p)
  1758.  
  1759. echivalenta :: Prop -> Prop -> Bool
  1760. echivalenta = undefined
  1761.  
  1762. test_echivalenta1 = True == (Var "P" :&: Var "Q") `echivalenta` (Not (Not (Var "P") :|: Not (Var "Q")))
  1763. test_echivalenta2 = False == (Var "P") `echivalenta` (Var "Q")
  1764. test_echivalenta3 = True == (Var "R" :|: Not (Var "R")) `echivalenta` (Var "Q" :|: Not (Var "Q"))
  1765.  
  1766.  
  1767.  
  1768. MODEL
  1769.  
  1770.  
  1771.  
  1772.  
  1773. data Linie = L [ Int ]
  1774. data Matrice = M [ Linie ]
  1775.  
  1776. -- liniiN (M [L[1,2,3], L[4,5], L[2,3,6,8], L[8,5,3]]) 3
  1777. -- [L[1,2,3], L[8,5,3]]
  1778.  
  1779. -- doarPozN (M [L[1,2,3], L[4,5], L[2,3,6,8], L[8,5,3]]) 3
  1780. -- True
  1781.  
  1782. -- doarPozN (M [L[1,2,-3], L[4,5], L[2,3,6,8], L[8,5,3]]) 3
  1783. -- False
  1784.  
  1785. -- verifica (M[L[1,2,3], L[4,5], L[2,3,6,8], L[8,5,3]]) 10
  1786. -- False
  1787.  
  1788. -- verifica (M[L[2,20,3], L[4,21], L[2,3,6,8,6], L[8,5,3,9]]) 25
  1789. -- True
  1790.  
  1791.  
  1792. -- M[L[1,2,3], L[4,5], L[2,3,6,8], L[8,5,3]]
  1793. -- 1 2 3
  1794. -- 4 5
  1795. -- 2 3 6 8
  1796. -- 8 5 3
  1797.  
  1798. --ex 1
  1799. verifica1 :: Linie -> Int -> Bool
  1800. verifica1 (L x) n = if length x == n then True else False
  1801.  
  1802. liniiN :: Matrice -> Int -> [Linie]
  1803. liniiN (M x) n = if n > 0 then [l | l <- x, verifica1 l n] else error "n mai mic sau egal cu 0"
  1804.  
  1805. --ex 2
  1806. verifica2 :: Linie -> Bool
  1807. verifica2 (L []) = True
  1808. verifica2 (L (x : xs)) = if x > 0 then verifica2 (L xs) else False
  1809.  
  1810. doarPozN :: Matrice -> Int -> Bool
  1811. doarPozN (M []) n = True
  1812. doarPozN (M (x : xs)) n = if verifica1 x n then verifica2 x && doarPozN (M xs) n else doarPozN (M xs) n
  1813.  
  1814. --ex 3
  1815. verifica3 :: Linie -> Int -> Bool
  1816. verifica3 (L x) n = if sum x == n then True else False
  1817.  
  1818. verifica :: Matrice -> Int -> Bool
  1819. verifica (M []) n = True
  1820. verifica (M (x : xs)) n = verifica3 x n && verifica (M xs) n
  1821.  
  1822. --ex 4
  1823. instance Show Matrice where
  1824. show (M []) = ""
  1825. show (M (linie : linii)) = show linie ++ "\n" ++ show(M linii)
  1826.  
  1827. instance Show Linie where
  1828. show (L []) = ""
  1829. show (L (x : xs)) = show x ++ " " ++ show (L xs)
  1830.  
  1831.  
  1832.  
  1833. -- doarPozN mat n = and [all (> 0) x | L x <- liniiN mat n]
  1834. -- verifica (M mat) n = foldr (&&) True [foldr (+) 0 x == n | L x <- mat]
  1835.  
  1836. --instance Show Matrice where
  1837. -- show (M []) = ""
  1838. -- show (M ((L x) : linii)) = concat (map (\temp -> show temp ++ " ") x) ++ "\n" ++ show (M xs)
  1839.  
  1840.  
  1841.  
  1842.  
  1843. LAB10
  1844.  
  1845.  
  1846. data Expr = Const Int -- integer constant
  1847. | Expr :+: Expr -- addition
  1848. | Expr :*: Expr -- multiplication
  1849. deriving Eq
  1850. showData :: Expr -> String
  1851. --showData x = show x
  1852. showData (Const x ) =show x
  1853. showData (e1 :*: e2) = "("++show e1 ++ " * " ++ show e2 ++")"
  1854. showData (e1 :+: e2) = "("++show e1 ++ " + " ++ show e2 ++")"
  1855.  
  1856. instance Show (Expr ) where
  1857. show=showData
  1858. --testare
  1859. evalExp :: Expr -> Int
  1860. evalExp (Const x) = x
  1861. evalExp ( ( e1) :+: ( e2) )= (evalExp e1) + (evalExp e2)
  1862. evalExp (( e1) :*: ( e2))=(evalExp e1) * (evalExp e2)
  1863.  
  1864. exp1 = ((Const 2 :*: Const 3) :+: (Const 0 :*: Const 5))
  1865. exp2 = (Const 2 :*: (Const 3 :+: Const 4))
  1866. exp3 = (Const 4 :+: (Const 3 :*: Const 3))
  1867. exp4 = (((Const 1 :*: Const 2) :*: (Const 3 :+: Const 1)) :*: Const 2)
  1868. test11 = evalExp exp1 == 6
  1869. test12 = evalExp exp2 == 14
  1870. test13 = evalExp exp3 == 13
  1871. test14 = evalExp exp4 == 16
  1872.  
  1873.  
  1874. data Operation = Add | Mult deriving (Eq, Show)
  1875. data Tree = Lf Int -- leaf
  1876. | Node Operation Tree Tree -- branch
  1877. deriving (Eq, Show)
  1878.  
  1879. --E2
  1880. evalArb :: Tree -> Int
  1881. evalArb (Lf x) = x
  1882. evalArb (Node Add tree1 tree2) = evalArb (tree1) + evalArb (tree2)
  1883. evalArb (Node Mult tree1 tree2) = evalArb (tree1) * evalArb (tree2)
  1884.  
  1885.  
  1886. --E3
  1887. expToArb :: Expr -> Tree
  1888. expToArb (Const x) = (Lf x)
  1889. expToArb (e1 :+: e2) = Node Add (expToArb(e1) ) (expToArb(e2) )
  1890. expToArb (e1 :*: e2 )= Node Mult ( expToArb(e1) ) (expToArb(e2) )
  1891.  
  1892. --testare
  1893. arb1 = Node Add (Node Mult (Lf 2) (Lf 3)) (Node Mult (Lf 0)(Lf 5))
  1894. arb2 = Node Mult (Lf 2) (Node Add (Lf 3)(Lf 4))
  1895. arb3 = Node Add (Lf 4) (Node Mult (Lf 3)(Lf 3))
  1896. arb4 = Node Mult (Node Mult (Node Mult (Lf 1) (Lf 2)) (Node Add (Lf 3)(Lf 1))) (Lf 2)
  1897. test21 = evalArb arb1 == 6
  1898. test22 = evalArb arb2 == 14
  1899. test23 = evalArb arb3 == 13
  1900. test24 = evalArb arb4 == 16
  1901.  
  1902.  
  1903. --E4
  1904. class MySmallCheck a where
  1905. smallValues :: [a]
  1906. smallCheck :: ( a -> Bool ) -> Bool
  1907. smallCheck prop = and [ prop x | x <- smallValues ]
  1908. instance MySmallCheck Expr where
  1909. smallValues=[exp1, exp2, exp3, exp4]
  1910.  
  1911.  
  1912.  
  1913. checkExp :: Expr -> Bool
  1914.  
  1915.  
  1916.  
  1917.  
  1918. double :: Int -> Int
  1919. double = undefined
  1920. triple :: Int -> Int
  1921. triple = undefined
  1922. penta :: Int -> Int
  1923. penta = undefined
  1924. test x = (double x + triple x) == (penta x)
  1925. myLookUp :: Int -> [(Int,String)]-> Maybe String
  1926. myLookUp = undefined
  1927. testLookUp :: Int -> [(Int,String)] -> Bool
  1928. testLookUp = undefined
  1929. -- testLookUpCond :: Int -> [(Int,String)] -> Property
  1930. -- testLookUpCond n list = n > 0 && n `div` 5 == 0 ==> testLookUp n list
  1931. data ElemIS = I Int | S String
  1932. deriving (Show,Eq)
  1933. myLookUpElem :: Int -> [(Int,ElemIS)]-> Maybe ElemIS
  1934. myLookUpElem = undefined
  1935. testLookUpElem :: Int -> [(Int,ElemIS)] -> Bool
  1936. testLookUpElem = undefined
  1937.  
  1938. -- categoria A - functii de baza
  1939. -- categoria B - functii din biblioteci (fara map, filter, fold)
  1940. -- categoria C - map, filter, fold
  1941.  
  1942. {- Catcgoria A. Functii de baza
  1943. div, mod :: Integral a => a -> a -> a
  1944. even, odd :: Integral a => a -> Bool
  1945. (+), (*), (-), (/) :: Num a => a -> a -> a
  1946. (<), (<=), (>), (>=) :: Ord => a -> a -> Bool
  1947. (==), (/=) :: Eq a => a -> a -> Bool
  1948. (&&), (||) :: Bool -> Bool -> Bool
  1949. not :: Bool -> Bool
  1950. max, min :: Ord a => a -> a -> a
  1951. isAlpha, isAlphaNum, isLower, isUpper, isDigit :: Char -> Bool
  1952. toLower, toUpper :: Char -> Char
  1953. digitToInt :: Char -> Int
  1954. ord :: Char -> Int
  1955. chr :: Int -> Char
  1956. Intervale
  1957. [first..], [first,second..], [first..last], [first,second..last]
  1958. -}
  1959.  
  1960. {- Categoria B. Functii din biblioteci
  1961. sum, product :: (Num a) => [a] -> a
  1962. sum [1.0,2.0,3.0] = 6.0
  1963. product [1,2,3,4] = 24
  1964.  
  1965. and, or :: [Bool] -> Bool
  1966. and [True,False,True] = False
  1967. or [True,False,True] = True
  1968.  
  1969. maximum, minimum :: (Ord a) => [a] -> a
  1970. maximum [3,1,4,2] = 4
  1971. minimum [3,1,4,2] = 1
  1972.  
  1973. reverse :: [a] -> [a]
  1974. reverse "goodbye" = "eybdoog"
  1975.  
  1976. concat :: [[a]] -> [a]
  1977. concat ["go","od","bye"] = "goodbye"
  1978.  
  1979. (++) :: [a] -> [a] -> [a]
  1980. "good" ++ "bye" = "goodbye"
  1981.  
  1982. (!!) :: [a] -> Int -> a
  1983. [9,7,5] !! 1 = 7
  1984.  
  1985. length :: [a] -> Int
  1986. length [9,7,5] = 3
  1987.  
  1988. head :: [a] -> a
  1989. head "goodbye" = 'g'
  1990.  
  1991. tail :: [a] -> [a]
  1992. tail "goodbye" = "oodbye"
  1993.  
  1994. init :: [a] -> [a]
  1995. init "goodbye" = "goodby"
  1996.  
  1997. last :: [a] -> a
  1998. last "goodbye" = 'e'
  1999.  
  2000. takeWhile :: (a->Bool) -> [a] -> [a]
  2001. takeWhile isLower "goodBye" = "good"
  2002.  
  2003. take :: Int -> [a] -> [a]
  2004. take 4 "goodbye" = "good"
  2005.  
  2006. dropWhile :: (a->Bool) -> [a] -> [a]
  2007. dropWhile isLower "goodBye" = "Bye"
  2008.  
  2009. drop :: Int -> [a] -> [a]
  2010. drop 4 "goodbye" = "bye"
  2011.  
  2012. elem :: (Eq a) => a -> [a] -> Bool
  2013. elem 'd' "goodbye" = True
  2014.  
  2015. replicate :: Int -> a -> [a]
  2016. replicate 5 '*' = "*****"
  2017.  
  2018. zip :: [a] -> [b] -> [(a,b)]
  2019. zip [1,2,3,4] [1,4,9] = [(1,1),(2,4),(3,9)
  2020. -}
  2021.  
  2022. {- Categoria C. Map, Filter, Fold
  2023. map :: (a -> b) -> [a] -> [b]
  2024. map (+3) [1,2] = [4,5]
  2025.  
  2026. filter :: (a -> Bool) -> [a] -> [a]
  2027. filter even [1,2,3,4] = [2,4]
  2028.  
  2029. foldr :: (a -> b -> b) -> b -> [a] -> b
  2030. foldr max 0 [1,2,3,4] = 4
  2031.  
  2032. (.) :: (b -> c) -> (a -> b) -> a -> c
  2033. ($) :: (a -> b) -> a -> b
  2034. (*2) . (+3) $ 7 = 20
  2035.  
  2036. flip :: (a -> b -> c) -> b -> a -> c
  2037. flip (-) 2 3 = 1
  2038. -}
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement