Download Practical 10 - OCaml 2 - Computing Science and Mathematics

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

Falcon (programming language) wikipedia , lookup

Subroutine wikipedia , lookup

Monad (functional programming) wikipedia , lookup

Recursion (computer science) wikipedia , lookup

Ringing artifacts wikipedia , lookup

Filter bank wikipedia , lookup

Dirac delta function wikipedia , lookup

Corecursion wikipedia , lookup

C syntax wikipedia , lookup

Functional programming wikipedia , lookup

APL syntax and symbols wikipedia , lookup

Function object wikipedia , lookup

C++ wikipedia , lookup

Standard ML wikipedia , lookup

Transcript
ComputingScienceandMathematics
CSCU9Y4Practical10
FunctionalProgramminginOCaml!
Asbefore,thefollowingonlineOCamlenvironmentsareavailableforuse.
a) https://try.ocamlpro.com
b) https://ocsigen.org/js_of_ocaml/2.7/files/toplevel/index.html
c) https://www.tutorialspoint.com/compile_ocaml_online.php
Theconfusionover‘::’isbecauseitisnotanoperator.Itis,instead,aconstructorthataddsan
elementtoalist.Thoughitisoftencalledthe“::operator,”itstruenameis“cons.”So,thelist
# [1;2;3];;
- : int list = [1; 2; 3]
canequivalentlybeconstructedbyanyofthefollowing:
# 1 :: (2 :: (3 :: [])) ;;
- : int list = [1; 2; 3]
# 1 :: 2 :: 3 :: [] ;;
- : int list = [1; 2; 3]
#
#
-
let my_lst = [2;3];;
: val my_lst = [2; 3]
1 :: [2;3];;
: int list = [1; 2; 3]
Bothconstructionsarepossiblebecause::isright-associative,sonestedparenstotherightare
unnecessary.Alsokeepinmindthat[]istheemptylist.Itispolymorphic,andsoisalsousedto
terminatelists.Thus,thestructurecontainingtheabovelistis
+---+---+
+---+---+
+---+---+
| 1 | *---->| 2 | *---->| 3 | *---->[]
+---+---+
+---+---+
+---+---+
(*Onmatching*)
PatternmatchinginOcamlcanbethoughtofassimilartotheimperativeswitchstatements.
However,OCaml’stypesystemmeansthatwecanmatch,notonlyagainstexactvalues,butalso
predicatesandothertypeconstructors!Forexample,
# let is_zero x =
match x with
| 0 -> true
| _ -> false (* The "_" pattern means "anything else". *)
;;
(* Also, match predicates, eg. return the positive of any negative value *)
# let abs x =
match x with
| x when x < 0 -> -x
| _ -> x
;;
(*TASK1*)
Re-writethefollowingrecursivefunctionusingpatternmatching.
# let rec sum_to x =
| if x = 0 then 0
| else x + sum_to (x -1)
;;
Inyournewversion,itisrecommendedthatallappearancesofxintheprediatesbewrittenas
x’(singlequotesaftercharactersarepermittedinidentifiernames).Why?Thisisjust
conventiontoindicatethattheparameterandpredicatevarsaredifferent.
Notethedifferencewithaprependedsinglequote,eg.’x ,thatmeans“anytype.”
(*TASK2*)
Imperativeswitchstatementsonlyworkwhentheyembedallpossible“cases.”Theeleganceof
OCaml’sinferenceengineisthatitcantellwhenacaseismissing!Considerthefunction,
(* Remove contiguous duplicates from a list. *)
# let rec destutter list =
match list with
| [] -> []
| hd1 :: hd2 :: tl ->
if hd1 = hd2 then destutter (hd2 :: tl)
else hd1 :: destutter (hd2 :: tl)
;;
thatreturnsa“notexhaustive”error.Enumerateallpossiblecases;fixthefunction!
Checkpoint
Show and explain your solutions to a demonstrator.
(*Higher-orderFunctions!*)
Justasregularfunctionstakedatatypesasparameters,ahigher-orderfunctiontakesafunction
asanargument.Sometimes,functionscanalsobereturned.Wow!
Yes,thiscanbedoneinimperativelanguages,eg.C’sfunctionpointers,thoughtheyare
complextowrite.Bycontrast,functionallanguagesmaketheirconstructionelegant.Hereisa
programwithhigher-orderfunctionthattakestwoparameters:onefunction,andonelist.
open Printf;;
print_string "Hello world!\n";;
(* filter returns a new list with f applied to each list element. *)
let rec filter f lst =
match lst with
| [] -> []
| hd :: tl -> (f hd) :: (filter f tl)
;;
(* Now call filter with an anonymous function; what is the outcome? *)
filter (fun x -> x * 2) [1; 2; 3; 4; 5];;
(* To see the output, one could type as follows. *)
List.iter (printf “%d “) (filter (fun x -> x * 2) [1; 2; 3; 4; 5]);;
Itisatthisstagethatfunctionalpowershouldstarttobecomeclear.Thefunctionfiltercanbe
usedtoapplyanysequenceofoperationsoneachelementinalist.WOW!
(*TASK3–Bonus/optional*)
Usingfilterasatemplate,writeyourownhigher-orderfunctionmy_filterthattakes
- abooleanfunction,i.e.itreturnstrueorfalse),sayf
- alist,saylst
andreturnsanewlistthatconsistsofelementsoflstsuchthatfreturnstrueonthatelement.
Inotherwords,
∀𝑒 ∈ 𝑙𝑠𝑡, 𝑒 ∈ 𝑙𝑠𝑡 ( if𝑓 𝑒 returns𝑡𝑟𝑢𝑒.
Useyournewfunctiontoreturnonlyevenintegersinalist.HINT:Theeasiestimplementation
consistsofanif/elseinsideofamatch.