Created
October 30, 2019 23:13
-
-
Save rand00/38cd27318080334d400cd851cddcfaf4 to your computer and use it in GitHub Desktop.
Why Is Array/Object Destructuring So Useful And How To Use It (a JS example of destructuring shown in OCaml)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(*took examples from https://youtu.be/NIq3qLaHCIs*) | |
let printf = Printf.printf | |
let example1 = | |
let alphabet = ['a'; 'b'; 'c'; 'd'; 'e'; 'f'] in | |
match alphabet with | |
| a :: b :: _ -> | |
printf "a = %c and b = %c\n" a b | |
let example2 = | |
let alphabet = ['a'; 'b'; 'c'; 'd'; 'e'; 'f'] in | |
match alphabet with | |
| a :: _ :: c :: rest -> | |
printf "a = %c and c = %c\n" a c (*.. + use rest*) | |
let example3 = | |
let alphabet = ['a'; 'b'; 'c'; 'd'; 'e'; 'f'] in | |
let numbers = [1; 2; 3; 4] in | |
let new_list = | |
[ alphabet |> List.map (fun v -> `Char v); | |
numbers |> List.map (fun v -> `Num v) ] | |
|> List.flatten | |
in new_list | |
let example4 = | |
let sum_and_multiply a b = a + b, a * b in | |
let sum, multiply = sum_and_multiply 2 3 in | |
() | |
type person = { | |
name : string; | |
age : int; | |
address : address | |
} | |
and address = { | |
city : string; | |
state : string; | |
} | |
let example5 = | |
let person_two = { | |
name = "Sally"; | |
age = 32; | |
address = { | |
city = "Somewhere else"; | |
state = "Another one of them"; | |
} | |
} | |
in | |
let { name; age } = person_two in | |
() (*...*) | |
let example6 = | |
let person_two = { | |
name = "Sally"; | |
age = 32; | |
address = { | |
city = "Somewhere else"; | |
state = "Another one of them"; | |
} | |
} | |
in | |
let { name = first_name; age } = person_two in | |
printf "first name = %s\n" first_name | |
let example7 = | |
let person_two = { | |
name = "Sally"; | |
age = 32; | |
address = { | |
city = "Somewhere else"; | |
state = "Another one of them"; | |
} | |
} | |
in | |
let { name = first_name; address = { city }} = person_two in | |
printf "city = %s\n" city | |
let example8 = | |
let person_two = { | |
name = "Sally"; | |
age = 32; | |
address = { | |
city = "Somewhere else"; | |
state = "Another one of them"; | |
} | |
} | |
in | |
let print_user { name; age } = | |
printf "name is %s and age is %d\n" name age | |
in | |
print_user person_two |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment