Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

F# Lambda Expressions

open System
//functions
let  multiply (x,y) = x*y
Console.WriteLine(multiply (5,2))


//range of numbers
let k =  [for x in 1..10-> x*x]
Console.WriteLine(k)

//point function
let m (a,b,c) = a+b*c
Console.WriteLine(m(2,3,4))

//recursive function
let rec fact x = if x <= 1 then 1 else x*fact(x-1)
Console.WriteLine (fact(5))

//mutually recursive function
let rec isOdd x = 
if x = 0 then false
elif x = 1 then true
else isEven(x-1)
and isEven x =
if x = 0 then true
elif x = 1 then false
else isOdd (x-1)
Console.WriteLine("_________")
Console.WriteLine( isOdd(5))

//swap function
let swap (a, b) = (b, a)
Console.WriteLine (swap(4,5))

//Square function
let dnumb = [for x in 1..5 -> x*2]
Console.WriteLine (dnumb)

//Values as functions
let square = fun x -> x*x
Console.WriteLine (square(3))


//pattern matching using a function *doesnt use match keyword
let rec factorial = function
    | n when n < 1 -> 1
    | n -> n * fact (n - 1) 
Console.WriteLine (fact(5))

let rec fibbonaci = function 
| x when x < 1 -> 1
| x -> fibbonaci (x-1) + fibbonaci (x-2)
Console.WriteLine(fibbonaci(7))

//pattern matching without a function *use match and with keywords
let isOdd x = (x%2 = 1)
let describeNo x = match isOdd x with
| true ->printfn "x is odd"
| false ->printfn"x is even"

describeNo 6

let rec fib n =
   match n with
   | 0 -> 0
   | 1 -> 1
   | _ -> fib (n - 1) + fib (n - 2)
for i = 1 to 10 do
   printfn "Fibonacci %d: %d" i (fib i)
   
let rec fac x = match x with
| x when x < 1 -> 1
| x -> x*fac(x-1)

Console.WriteLine(fac(5))

//Lists
//Creating lists
let list1 = [1; 2; 3; 4; 5; 6; 7; 8; 9; 10]

//[] the last element should be empty
let list2 = 1::2::3::4::5::6::7::8::9::10::[]
Console.WriteLine (list1)
Console.WriteLine(list2)

//The number of elements
Console.WriteLine(List.length list1)

//The sum of the elements in the list
Console.WriteLine(List.sum list1)

//prints out the head = first element
Console.WriteLine(List.head list1)

//prints out the tail = the rest of the elements
Console.WriteLine(List.tail [1;2;3;4])

//Create list with range
let list3 = [1..2..10]
Console.WriteLine(list3)

//Yield
let numbersNear x = [
yield x-1
yield x
yield x+1
]
Console.WriteLine(numbersNear 4)

//do yield can be used in 2 ways 
//1)using do yield
let list4 = [ for a in 1 .. 10 do yield (a * a) ]
Console.WriteLine(list4)

//2) using ->
let list5  = [for x in 1 .. 10 -> x*2 ]
Console.WriteLine(list5)

let list = [for a in 1 .. 5 do
match a with
| 3 -> yield! ["p"; "c"; "l"]
| _ -> yield a.ToString ()
]
Console.WriteLine(list)

Advertisements
Loading...

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.