Programming paradigms


Информатика, кибернетика и программирование

Progrmming prdigms. The word progrmming prdigm is used in severl different lthough relted menings in computer science. Progrmming prdigm pttern tht serves s school of thoughts for progrmming of computers. Progrmming technique relted to n lgorithmic ide for solving prticulr clss of problems.



45 KB

0 чел.

Lecture 3. Programming paradigms1.

The word programming paradigm is used in several different, although related meanings in computer science.

Programming paradigm – a pattern that serves as a school of thoughts for programming of computers.

Programming technique – related to an algorithmic idea for solving a particular class of problems.

Programming style – the way we express ourselves in a computer program. Related to elegance or lack of elegance

Programming culture – the totality of programming behavior, which often is tightly related to a family of programming languages. The sum of a main paradigm, programming styles, and certain programming techniques.

There are four main programming paradigms and a number of minor programming paradigms.

Main programming paradigms:

  •  The imperative paradigm
  •  The functional paradigm
  •  The logical paradigm
  •  The object-oriented paradigm

Other possible programming paradigms:

  •  The visual paradigm
  •  One of the parallel paradigms
  •  The constraint based paradigm

3.1 Overview of the imperative paradigm.

The word “imperative” can be used both as an adjective and as a noun. As an adjective it means 'expressing a command or plea'. In other words, asking for something to be done. As a noun, an imperative is a command or an order.

Characteristics of the imperative paradigm:

  •  Discipline and idea
    •  Digital hardware technology and the ideas of Von Neumann
    •  Incremental change of the program state as a function of time.
    •  Execution of computational steps in an order governed by control structures
      •  We call the steps for commands
    •  Straightforward abstractions of the way a traditional Von Neumann computer works
    •  Similar to descriptions of everyday routines, such as food recipes and car repair
    •  Typical commands offered by imperative languages
      •  Assignment, IO, procedure calls
    •  Language representatives
      •  Fortran, Algol, Pascal, Basic, C
    •  The natural abstraction is the procedure
      •  Abstracts one or more actions to a procedure, which can be called as a single command.
      •  Procedural programming

Several names are used for the computational steps in an imperative language. The word statement is often used with the special computer science meaning “an elementary instruction in a source language”. The word instruction is another possibility. This word is preferably devoted to the computational steps performed at the machine level. The word “command” is used for the imperatives in a high level imperative programming language.

A procedure abstracts one or more actions to a procedure, which can be activated as a single action.

3.2 Overview of the functional paradigm

Evaluate an expression and use the resulting value for something.

Characteristics of the functional paradigm:

  •  Discipline and idea
    •  Mathematics and the theory of functions
    •  The values produced are non-mutable
      •  Impossible to change any constituent of a composite value
      •  As a remedy, it is possible to make a revised copy of composite value
    •  Atemporal
      •  Time only plays a minor role compared to the imperative paradigm
    •  Applicative
      •  All computations are done by applying (calling) functions
    •  The natural abstraction is the function
      •  Abstracts a single expression to a function which can be evaluated as an expression
    •  Functions are first class values
      •  Functions are full-fledged data just like numbers, lists, ...
    •  Fits well with computations driven by needs
      •  Opens a new world of possibilities

3.3 Overview of the logic paradigm

Answer a question via search for a solution.

Characteristics of the logic paradigm:

  •  Discipline and idea
    •  Automatic proofs within artificial intelligence
    •  Based on axioms, inference rules, and queries.
    •  Program execution becomes a systematic search in a set of facts, making use of a set of inference rules

3.4 Overview of the object-oriented paradigm

Send messages between objects to simulate the temporal evolution of a set of real world phenomena.

Characteristics of the object-oriented paradigm:

  •  Discipline and idea
    •  The theory of concepts, and models of human interaction with real world phenomena
    •  Data as well as operations are encapsulated in objects
    •  Information hiding is used to protect internal properties of an object
    •  Objects interact by means of message passing
      •  A metaphor for applying an operation on an object
    •  In most object-oriented languages objects are grouped in classes
      •  Objects in classes are similar enough to allow programming of the classes, as opposed to programming of the individual objects
      •  Classes represent concepts whereas objects represent phenomena
    •  Classes are organized in inheritance hierarchies
      •  Provides for class extension or specialization

3.5 The visual paradigm

The visual paradigm or visual programming is writing programs in a language which manipulates visual information or supports visual interaction. Visual programming could be:

  •  writing programs in a visual programming language, or
  •  writing programs in a visual programming environment.

Visual programming language (VPL). Any programming language that allows the user to specify a program in a two(or more)-dimensional way. Conventional textual languages are not considered two-dimensional since the compiler or interpreter processes them as one-dimensional streams of characters. A VPL allows programming with visual expressions - spatial arrangements of textual and graphical symbols.

VPLs may be further classified, according to the type and extent of visual expression used, into icon-based languages, form-based languages and diagram languages. Visual programming environments provide graphical or iconic elements which can be manipulated by the user in an interactive way according to some specific spatial grammar for program construction.

A visually transformed language is a non-visual language with a superimposed visual representation. Naturally visual languages have an inherent visual expression for which there is no obvious textual equivalent.

Visual Basic, Visual C++ and the entire Microsoft Visual family are not, despite their names, visual programming languages. They are textual languages which use a graphical GUI builder to make programming interfaces easier. The user interface portion of the programming environment is visual, the languages are not. Because of the confusion caused by the multiple meanings of the term “visual programming”, the term “executable graphics” has been proposed as an alternative to VPL.

Some examples of visual programming languages are Prograph, Pict, Tinkertoy, Fabrik, CODE 2.0 and Hyperpascal.

Visual programming environment. Software which allows the use of visual expressions (such as graphics, drawings, animation or icons) in the process of programming. These visual expressions may be used as graphical interfaces for textual programming languages. They may be used to form the syntax of new visual programming languages leading to new paradigms such as programming by demonstration or they may be used in graphical presentations of the behaviour or structure of a program.

3.6 Common parallel programming paradigms2

Parallel computing using a system such as parallel virtual machine (PVM) may be approached from three fundamental viewpoints, based on the organization of the computing tasks. Within each, different workload allocation strategies are possible.

The first and most common model for PVM applications can be termed “crowd” computing: a collection of closely related processes, typically executing the same code, perform computations on different portions of the workload, usually involving the periodic exchange of intermediate results. This paradigm can be further subdivided into two categories:

The master-slave (or host-node) model in which a separate “control” program termed the master is responsible for process spawning, initialization, collection and display of results, and perhaps timing of functions. The slave programs perform the actual computation involved; they either are allocated their workloads by the master (statically or dynamically) or perform the allocations themselves.

The node-only model where multiple instances of a single program execute, with one process (typically the one initiated manually) taking over the noncomputational responsibilities in addition to contributing to the computation itself.

The second model supported by PVM is termed a “tree”' computation. In this scenario, processes are spawned (usually dynamically as the computation progresses) in a tree-like manner, thereby establishing a tree-like, parent-child relationship (as opposed to crowd computations where a star-like relationship exists). This paradigm, although less commonly used, is an extremely natural fit to applications where the total workload is not known a priori, for example, in branch-and-bound algorithms, alpha-beta search, and recursive “divide-and-conquer”' algorithms.

The third model, termed “hybrid”, can be thought of as a combination of the tree model and crowd model. Essentially, this paradigm possesses an arbitrary spawning structure: that is, at any point during application execution, the process relationship structure may resemble an arbitrary and changing graph.

These three classifications are made on the basis of process relationships, though they frequently also correspond to communication topologies. Nevertheless, in all three, it is possible for any process to interact and synchronize with any other. Further, the choice of model is application dependent and should be selected to best match the natural structure of the parallelized program

3.7 The constraint based paradigm

In computer science, constraint programming is a programming paradigm wherein relations between variables are stated in the form of constraints. Constraints differ from the common primitives of imperative programming languages in that they do not specify a step or sequence of steps to execute, but rather the properties of a solution to be found. This makes constraint programming a form of declarative programming. The constraints used in constraint programming are of various kinds: those used in constraint satisfaction problems (e.g. “A or B is true”), those solved by the simplex algorithm (e.g. “x ≤ 5”), and others. Constraints are usually embedded within a programming language or provided via separate software libraries.

Constraint programming can be expressed in the form of constraint logic programming, which embeds constraints into a logic program. This variant of logic programming is due to Jaffar and Lassez, who extended in 1987 a specific class of constraints that were introduced in Prolog II. The first implementations of constraint logic programming were Prolog III, CLP(R), and CHIP.

Instead of logic programming, constraints can be mixed with functional programming, term rewriting, and imperative languages. Programming languages with built-in support for constraints include Oz (functional programming) and Kaleidoscope (imperative programming). Mostly, constraints are implemented in imperative languages via constraint solving toolkits, which are separate libraries for an existing imperative language.

The constraints used in constraint programming are typically over some specific domains. Some popular domains for constraint programming are:

  •  boolean domains, where only true/false constraints apply (SAT problem)
  •  integer domains, rational domains
  •  linear domains, where only linear functions are described and analyzed (although approaches to non-linear problems do exist)
  •  finite domains, where constraints are defined over finite sets
  •  mixed domains, involving two or more of the above

Finite domains is one of the most successful domains of constraint programming. In some areas (like operations research) constraint programming is often identified with constraint programming over finite domains.

1 http://people.cs.aau.dk/~normark/prog3-03/html/notes/paradigms-book.html

2 http://www.netlib.org/pvm3/book/node28.html


А также другие работы, которые могут Вас заинтересовать

44370. Покрытие пиковых нагрузок энергосистем 1.07 MB
  Электроэнергетика России имея общую мощность электростанций 210 млн. Так основные параметры и единичная мощность основного генерирующего оборудования и линий электропередач используемых в отрасли находятся на уровне развитых стран мира. кВтч а установленная мощность электростанций увеличится примерно на 50 процентов и достигнет 320млн. Первая на Енисее Красноярская ГЭС с бетонной плотиной длиной 1100м и высотой 120 м начала работать на полную мощность и теперь ее 12 гидроагрегатов вырабатывают в год в среднем 204 млрд.
44372. Анализ характеристик микромеханического гироскопа в режиме автоколебания 7.18 MB
  Перечень принятых обозначений и сокращений АД амплитудный детектор АМ амплитудная модуляция АФХ амплитуднофазовая характеристика АХ амплитудная характеристика АЦП аналогоцифровой преобразователь ВМ временная модуляция ДП датчик положения ДПИ датчик первичной информации ДС датчик силы ИМ инерционная масса К компаратор Кл ключ КП компенсирующий преобразователь МК микроконтроллер ММГ ...
44373. Аналіз діяльності ресторанного підприємства ТОВ Фантастік Інтернейшнл на прикладі Ресторану «Гімалаї» 143.67 KB
  Під час проходження практики я дізналася про різноманітні аспекти ресторанного господарства. Я отримала повну інформацію про правила здійснення торговельної діяльності, особливості національної кухні Індії, обслуговування населення в індійському стилі, порядок розрахунку зі споживачами. Загалом можу сказати, що робота в ресторані «Гімалаї» відображає сучасний рівень обслуговуваня населення в ресторанах України.
44374. Проектирование и разработка сайта интернет-представительства ООО «ХХХ» 1.98 MB
  Компании разрабатывают новые средства контакта со своими потенциальными потребителями и стараются размещать свои рекламные сообщения там где их аудитория проводит большую часть своего времени: на отраслевых развлекательных и новостных порталах в блогах и социальных сетях. Dremwever программный продукт от компании dobe. Кроме того разработчики компании dobe обновили движок WebKit улучшив поддержку видео и аудио На сегодняшний момент последней версией является Dremwever CS5. MySQL является собственностью компании Orcle Corportion...
44375. Особенности кредитной политики Сбербанка России по обслуживанию физических лиц 1.07 MB
  В связи с этим тщательный отбор заемщиков анализ условий выдачи кредита постоянный контроль за финансовым состоянием заемщика за способностью погасить кредит являются одной из основополагающих составляющих финансового благополучия банка. Первая часть работы посвящена теоретическим аспектам кредитования физических лиц в коммерческих банках а именно функциям роли сущности и видам кредита. В этой части дана общая характеристика экономической деятельности Сберегательного банка как старейшего и неоднократно подтвердившего репутацию самого...
44376. Обществознание. Процессы общественного строя 309.15 KB
  Природа – естественная среда обитания общества во всем бесконечном разнообразии своих проявлений, обладающая своими, не зависящими от воли и желаний человека, законами. Общество – обособившаяся от природы, но тесно связанная с ней часть материального мира, которая состоит из индивидуумов, обладающих волей и сознанием, и включает в себя способы взаимодействия людей и формы их объединения.
44377. ТЕОРІЯ АРХІТЕКТУРИ. Л.М. Бармашина 9.17 MB
  Викладено основні теоретичні аспекти архітектурної композиції. Розглянуто наступні групи питань: конструктивні системи несучих та інших конструкцій, зокрема стійково-балкова, склепінна, консольна та інші тектонічні системи, а також особливості тектоніки різних просторових конструкцій; теорія кольору в архітектурній композиції, просторові та психологічні властивості кольорів, колірна композиція, кольорове вирішення міської забудови, композиційні властивості архітектурного простору.
44378. Совершенствование механизма возмещения НДС по экспортным операциям на предприятии ООО «Яснополянская фабрика тары и упаковки» 664 KB
  На практике почти невозможно выделить добавленную стоимость в общей стоимости продукции (работ, услуг), поэтому для упрощения расчетов за объект обложения налогом на добавленную стоимость принимается не добавленная стоимость, а весь оборот по реализации, включая стоимость списанных на издержки производства и обращения материальных затрат (без учета уплаченного за них НДС)