Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Exercise 4.3 – List function
- // Define a function pclIncList that adds one to each element in a list of integers. You
- // are not allowed to use the standard F# functions. Use recursion and pattern matching.
- // For example, pclIncList [2; 3; 1; 4 ] should return [3; 4; 2; 5 ]
- open System
- let pclIncList (list) =
- [for i in list do yield i + 1]
- printfn "%A" (pclIncList [2; 3; 1; 4 ])
- Console.ReadKey() |> ignore
- // Exercise 4.4 – List function
- // a. Define a function, pclMap that applies an arbitrary function f to the elements in a list.
- open System
- let add2(n)= n + 2
- let pclMap (f, list) =
- let output = list |> List.map (fun x -> f(x))
- output
- printfn "%A" (pclMap(add2, [2; 3; 1; 4 ]))
- Console.ReadKey() |> ignore
- // b. Define a function pclIncListWithMap that changes the pclIncList you defined previously in 4.3 to use pclMap defined above.
- open System
- let pclMap (f, list) =
- let output = list |> List.map (fun x -> f(x))
- output
- let pclIncListWithMap(list) =
- let add1(n)= n + 1
- pclMap(add1, [2; 3; 1; 4 ])
- printfn "%A" (pclIncListWithMap([2; 3; 1; 4 ]))
- Console.ReadKey() |> ignore
- // Exercise 4.5 – List function
- // a. Define a function, pclFilter that removes all elements from a list that do not satisfy a given predicate.
- // b. Define a function pclEven that returns true for even numbers.
- // c. Test the functions:
- //For example, pclFilter pclEven [0; 1; 2; 3; 4; 5;6;7;8;9 ] should return [0; 2; 4;6;8
- open System
- let pclEven(x) =
- if x % 2 = 0 then true
- else false
- let pclFilter (condition, list)=
- let output = list |> List.filter (fun x -> condition (x))
- output
- printfn "%A" (pclFilter (pclEven, [1; 2; 3; 4; 5; 6 ;7 ;8 ;9]))
- Console.ReadKey() |> ignore
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement