Обзор языка Standard ML Сергей Романенко Moscow Computer Science School 20-22 сентября 2005 г.
История языка ML • Разр...
33 downloads
759 Views
109KB Size
Report
This content was uploaded by our users and we assume good faith they have the permission to share this book. If you own the copyright to this book and it is wrongfully on our website, we offer a simple DMCA procedure to remove your content from our site. Start by pressing the button below!
Report copyright / DMCA form
Обзор языка Standard ML Сергей Романенко Moscow Computer Science School 20-22 сентября 2005 г.
История языка ML • Разработан в Эдинбурге (1974, Robin Milner и его группа) как мета-язык для системы верификации программ • Вырос в универсальный (general-purpose) язык программирования • Standard ML (1990) – Definition of Standard ML (Milner, Tofte, Harper, MIT Press, 1990)
• Standard ML (1997) – The Definition of Standard ML (Revised) (Milner, Tofte, Harper, MacQueen, MIT Press, 1997)
Реализации SML-я • Standard ML of New Jersey (SML/NJ) – http://www.smlnj.org/
• Moscow ML – http://www.dina.dk/~sestoft/mosml.html (based on the run-time system of Caml Light http://pauillac.inria.fr/caml/distrib-caml-light-eng.html
• SML.NET – http://www.cl.cam.ac.uk/Research/TSG/SMLNET/
• etc…
Особенности SML • Статическая типизация • Автоматическое распознавание/выведение типов (type inference) • Рекурсивные типы данных • Параметрический полиморфизм • Сопоставление с образцом (pattern matching) • Обработка исключений (exception handling) • Возможность использовать императивные средства программирования • Модульность: структуры, сигнатуры и функторы (structures, signatures and functors)
"Hello world" D:\mosml\bin>mosml Moscow ML version 2.00 (June 2000) Enter `quit();' to quit. - "Hello World"; > val it = "Hello World" : string - 3+4; > val it = 7 : int - 3+ 4; > val it = 7 : int
Первичные типы (basic types) • int 125 • real
~13
3.14
0.01
~1.2E12
• string "Andrew" "one\ntwo\nthree" • char #"a"
#" "
• bool true
false
#"\n"
7E~5
Привязки переменных к значениям (bindings) > >
val val val val
a a b b
= = = =
2; 2 : int 3; 3 : int
- a+b; > val it = 5 : int - val b = b+1; > val b = 4 : int
Определения функций > >
fun double x = 2*x; val double = fn : int -> int double 6; val it = 12 : int
> >
fun val inc val
> >
fun adda s = s ^ "a"; val adda = fn : string -> string adda "tub"; val it = "tuba" : string
inc x = x+1; inc = fn : int -> int 100; it = 101 : int
Кортежи/n-ки (tuples) - (2,"Andrew"); > val it = (2, "Andrew") : int * string > >
fun average(x,y) = (x+y)/2.0; val average = fn : real * real -> real average(3.1, 3.2); val it = 3.15 : real
- fun addvect((x1,y1),(x2,y2)) = (x1+x2, y1+y2); > val addvect = fn : (int * int) * (int * int) -> int * int - addvect ((1,2),(3,4)); > val it = (4, 6) : int * int
Списки (lists) - [1,2,3]; > val it = [1, 2, 3] : int list - ["Andrew","Ben"]; > val it = ["Andrew", "Ben"] : string list - [(2,3),(2,2),(9,1)]; > val it = [(2, 3), (2, 2), (9, 1)] : (int * int) list - [[],[1],[1,2]]; > val it = [[], [1], [1, 2]] : int list list
Конструкторы списков (list constructors) > > >
nil; val 'a it = [] : 'a list 1::nil; val it = [1] : int list 2::(1::nil); val it = [2, 1] : int list
- fun upto(m,n) = if m>n then nil else m :: upto(m+1,n); > val upto = fn : int * int -> int list - upto(2,5); > val it = [2, 3, 4, 5] : int list
Сопоставление с образцом (pattern matching) - val (d,e) = (2,"two"); > val d = 2 : int val e = "two" : string - val [one,two,three] = [1,2,3]; > val one = 1 : int val two = 2 : int val three = 3 : int - fun prod [] = 1 | prod (n :: ns) = n * (prod ns); > val prod = fn : int list -> int - prod [2,3,5]; > val it = 30 : int
Полиморфизм (polymorphism) - fun len nil = 0 | len (x::xs) = 1 + len xs; > val 'a len = fn : 'a list -> int - len [[1,2,3],[4,5]]; > val it = 2 : int - len ["one","two","three"]; > val it = 3 : int - fun append ([], ys) = ys | append ((x::xs), ys) = x :: append(xs,ys); > val 'a append = fn : 'a list * 'a list -> 'a list - append ([1,2,3],[4,5]); > val it = [1, 2, 3, 4, 5] : int list
Закарривание (currying) > >
fun add(x,y) = x+y; val add = fn : int * int -> int add(2,3); val it = 5 : int
> >
fun addc x y = x+y; val addc = fn : int -> int -> int addc 2 3; val it = 5 : int
> >
val add10 = addc 10; val add10 = fn : int -> int add10 50; val it = 60 : int
Безымянные функции - val mul2 = fn x => 2*x; > val mul2 = fn : int -> int - mul2 30; > val it = 60 : int - fun addc x = fn y => x+y; > val addc = fn : int -> int -> int - (addc 10) 30; > val it = 40 : int - addc 10 30; > val it = 40 : int
Функции высших порядков (higher-order functions) - fun map f [] = [] | map f (x::xs) = f x :: map f xs; > val ('a, 'b) map = fn : ('a -> 'b) -> 'a list -> 'b list - map (fn x => 2*x) [1,2,3,4]; > val it = [2, 4, 6, 8] : int list - fun filter p [] = [] | filter p (x::xs) = if p x then x :: filter p xs else filter p xs; > val 'a filter = fn : ('a -> bool) -> 'a list -> 'a list - filter (fn x => x > 0) [~1,0,1,2]; > val it = [1, 2] : int list
Определяемые типы данных (the datatype declaration) - datatype direction = > datatype direction con East = East con North = North con South = South con West = West - fun | | | > val
right right right right right
North | East | South | West; : : : :
direction direction direction direction
North = East East = South South = West West = North; = fn : direction -> direction
- right South; > val it = West : direction
Типы данных с "начинкой" (data types which carry data) - datatype intTree = Tip of int | Fork of intTree * intTree; > datatype intTree con Fork = fn : intTree * intTree -> intTree con Tip = fn : int -> intTree - val t = Fork(Tip 2, Tip 3); > val t = Fork(Tip 2, Tip 3) : intTree - fun sumIntTree (Tip n) = n | sumIntTree (Fork(x,y)) = sumIntTree x + sumIntTree y; > val sumIntTree = fn : intTree -> int - sumIntTree t; > val it = 5 : int
Полиморфные (polymorphic) типы данных - datatype 'a tree = Tip of 'a | Fork of 'a tree * 'a tree; > datatype 'a tree = con 'a Fork = fn : 'a tree * 'a tree -> 'a tree con 'a Tip = fn : 'a -> 'a tree - fun flip (Tip x) = Tip x | flip (Fork(x,y)) = Fork(flip(y),flip(x)); > val 'a flip = fn : 'a tree -> 'a tree - flip (Fork(Tip 2, Tip 3)); > val it = Fork(Tip 3, Tip 2) : int tree - flip (Fork(Tip "a", Tip "b")); > val it = Fork(Tip "b", Tip "a") : string tree
Модули (Modules) • Структура (structure) является "контейнером" для группы взаимосвязанных типов, значений и других структур • Сигнатура (signature) описывает класс структур • Функтор (functor) берет структуры в качестве аргумента и порождает из них новые структуры – structure ~ value – signature ~ type – functor ~ function
Структуры (structures) structure Complex = struct type t = real*real; val zero = (0.0,0.0); fun sum ((x,y),(x'y')) = fun diff ((x,y),(x'y')) = fun prod ((x,y),(x'y')) = fun recip ((x,y),(x'y')) = let val t = x*x + y*y in (x/t, ~y/t) end; fun quo (z,z') = prod(z, end;
(x+x',y+y') : t; (x-x',y-y') : t; (x*x'-y*y',x*y'+x'*y) : t;
recip z');
Сигнатуры (signatures) signature ARITH = sig type t val zero : t val sum : t * t val diff : t * t val prod : t * t val quo : t * t end;
-> -> -> ->
t t t t
structure Rational : ARITH = struct type t = int*int; val zero = (0,1); ... end;
Функторы (functors) signature ZSP = sig type t val zero : t val sum : t * t -> t val prod : t * t -> t end; functor MatrixZSP(Z: ZSP) : ZSP = struct type t = Z.t list list; val zero = []; fun sum (rowsA, rowsB) = ... Z.sum ... fun prod (rowsA, rowsB) = ... Z.Zero ... Z.sum ... Z.prod end; structure IntMatrix = MatrixZSP(IntZSP);