Advertisement
biswasrohit20

f# Ex 4

May 20th, 2021
1,907
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
F# 1.79 KB | None | 0 0
  1. // Exercise 4.3 – List function
  2. // Define a function pclIncList that adds one to each element in a list of integers. You
  3. // are not allowed to use the standard F# functions. Use recursion and pattern matching.
  4. // For example, pclIncList [2; 3; 1; 4 ] should return [3; 4; 2; 5 ]
  5.  
  6.  
  7.  
  8. open System
  9.  
  10. let pclIncList (list) =
  11.     [for i in list do yield i + 1]
  12.  
  13. printfn "%A" (pclIncList [2; 3; 1; 4 ])
  14. Console.ReadKey() |> ignore
  15.  
  16.  
  17.  
  18. // Exercise 4.4 – List function
  19. // a. Define a function, pclMap that applies an arbitrary function f to the elements in a list.
  20.  
  21.  
  22. open System
  23.  
  24. let add2(n)= n + 2
  25.  
  26. let pclMap (f, list) =
  27.     let output = list |> List.map (fun x -> f(x))
  28.     output
  29.  
  30. printfn "%A" (pclMap(add2,  [2; 3; 1; 4 ]))
  31. Console.ReadKey() |> ignore
  32.  
  33. // b. Define a function pclIncListWithMap that changes the pclIncList you defined previously in 4.3 to use pclMap defined above.
  34.  
  35.  
  36. open System
  37.  
  38.  
  39. let pclMap (f, list) =
  40.     let output = list |> List.map (fun x -> f(x))
  41.     output
  42.  
  43. let pclIncListWithMap(list) =
  44.     let add1(n)= n + 1
  45.     pclMap(add1,  [2; 3; 1; 4 ])
  46.  
  47. printfn "%A" (pclIncListWithMap([2; 3; 1; 4 ]))
  48. Console.ReadKey() |> ignore
  49.  
  50.  
  51.  
  52. // Exercise 4.5 – List function
  53. // a. Define a function, pclFilter that removes all elements from a list that do not satisfy a given predicate.
  54. // b. Define a function pclEven that returns true for even numbers.
  55. // c. Test the functions:
  56. //For example, pclFilter pclEven [0; 1; 2; 3; 4; 5;6;7;8;9 ] should return [0; 2; 4;6;8
  57.  
  58.  
  59.  
  60.  
  61.  
  62. open System
  63.  
  64. let pclEven(x) =
  65.     if x % 2 = 0 then true
  66.     else false
  67.    
  68. let pclFilter (condition, list)=
  69.     let output = list |> List.filter (fun x -> condition (x))
  70.     output
  71.  
  72.  
  73. printfn "%A" (pclFilter (pclEven, [1; 2; 3; 4; 5; 6 ;7 ;8 ;9]))
  74. Console.ReadKey() |> ignore
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement