Wednesday, May 7, 2014

Functional Programming F# makeAbsolute

Suppose L is a List of integers write a function in F# called makeAbsolute that returns a new list where every element is non-negative

for Example : L = [1;-2;3;0;-5]
new L will be L = [1;2;3;0;5]

let  rec  makeAbsolute (L) =
     match L with
| [  ] -> [ ] // base case if the list is empty return an empty list
|  _ ->  if L.Head < 0 // if the head of the list is negative
            then -L.Head :: makeAbsolute(L.Tail) // negate the head of the list to make it positive then //concatenate to the list
            else   L.Head :: makeAbsolute(L.Tail)//other wise concatenate normal element to the list

Another way in high functional programming

let abs(x) = if x< 0 then -x else x  // create a function that convert negative element to positive

let  rec makeAbsolute(L) =
  match L with
 | [  ] -> [ ] //again base case if the list is empty return an empty list
 |  _   -> abs(L.Head) :: makeAbsolute(L.Tail) // apply the abs function to the head of the list then recursively //apply to all element in the list



No comments:

Post a Comment