The Flix type and effect system supports Hindley-Milner-style type inference. The system separates pure and impure code: if an expression is typed as pure then it cannot produce an effect at run-time. Higher-order functions can enforce that they are given pure (or impure) function arguments. The type and effect system supports effect polymorphism[7][8] which means that the effect of a higher-order function may depend on the effect(s) of its argument(s).
Flix supports Datalog programs as first-class values. A Datalog program value, i.e. a collection of Datalog facts and rules, can be passed to and returned from functions, stored in data structures, and composed with other Datalog program values. The minimal model of a Datalog program value can be computed and is itself a Datalog program value. In this way, Flix can be viewed as a meta programming language for Datalog. Flix supports stratified negation and the Flix compiler ensures stratification at compile-time.[9] Flix also supports an enriched form of Datalog constraints where predicates are given lattice semantics.[10][11][12][13]
Overview
Flix is a programming language in the ML-family of languages. Its type and effect system is based on Hindley-Milner with several extensions, including row polymorphism and Boolean unification. The syntax of Flix is inspired by Scala and uses short keywords and curly braces. Flix supports uniform function call syntax which allows a function call f(x, y, z) to be written as x.f(y, z). The concurrency model of Flix is inspired by Go and based on channels and processes. A process is a light-weight thread that does not share (mutable) memory with another process. Processes communicate over channels which are bounded or unbounded queues of immutable messages.
While many programming languages support a mixture of functional and imperative programming, the Flix type and effect system tracks the purity of every expression making it possible to write parts of a Flix program in a purely functional style with purity enforced by the effect system.
Flix supports tail call elimination which ensures that function calls in tail position never consume stack space and hence cannot cause the call stack to overflow.[17] Since the JVM instruction set lacks explicit support for tail calls, such calls are emulated using a form of reusable stack frames.[18] Support for tail call elimination is important since all iteration in Flix is expressed through recursion.
The Flix compiler disallows most forms of unused or redundant code, including: unused local variables, unused functions, unused formal parameters, unused type parameters, and unused type declarations, such unused constructs are reported as compiler errors.[19]Variable shadowing is also disallowed. The stated rationale is that unused or redundant code is often correlated with erroneous code[20]
The following program prints "Hello World!" when compiled and executed:
defmain():Unit\IO=println("Hello World!")
The type and effect signature of the main function specifies that it has no parameters, returns a value of type Unit, and that the function has the IO effect, i.e. is impure. The main function is impure because it invokes printLine which is impure.
Algebraic data types and pattern matching
The following program fragment declares an algebraic data type (ADT) named Shape:
enumShape{caseCircle(Int32),// has circle radiuscaseSquare(Int32),// has side lengthcaseRectangle(Int32,Int32)// has height and width}
The ADT has three constructors: Circle, Square, and Rectangle.
The following program fragment uses pattern matching to destruct a Shape value:
The following program fragment defines a higher-order function named twice that when given a function f from Int to Int returns a function that applies f to its input two times:
deftwice(f:Int32->Int32):Int32->Int32=x->f(f(x))
We can use the function twice as follows:
twice(x->x+1)(0)
Here the call to twice(x -> x + 1) returns a function that will increment its argument two times. Thus the result of the whole expression is 0 + 1 + 1 = 2.
Parametric polymorphism
The following program fragment illustrates a polymorphic function that maps a function f: a -> b over a list of elements of type a returning a list of elements of type b:
The map function recursively traverses the list l and applies f to each element constructing a new list.
Flix supports type parameter elision hence it is not required that the type parameters a and b are explicitly introduced.
Extensible records
The following program fragment shows how to construct a record with two fields x and y:
defpoint2d():{x:Int32,y:Int32}={x=1,y=2}
Flix uses row polymorphism to type records. The sum function below takes a record that has x and y fields (and possibly other fields) and returns the sum of the two fields:
defsum(r:{x:Int32,y:Int32|rest}):Int=r.x+r.y
The following are all valid calls to the sum function:
sum({x=1,y=2})sum({y=2,x=1})sum({x=1,y=2,z=3})
Notable features
Polymorphic effects
The Flix type and effect system separates pure and impure expressions.[5][22][23] A pure expression is guaranteed to be referentially transparent. A pure function always returns the same value when given the same argument(s) and cannot have any (observable) side-effects.
For example, the following expression is of type Int32 and has the empty effect set {}, i.e. it is pure:
1+2:Int32\{}
whereas the following expression has the IO effect, i.e. is impure:
println("Hello World"):Unit\IO
A higher-order function can specify that a function argument must be pure, impure, or that it is effect polymorphic.
For example, the definition of Set.exists requires that its function argument f is pure:
// The syntax a -> Bool is short-hand for a -> Bool \ {}defexists(f:a->Bool,xs:Set[a]):Bool=...
The requirement that f must be pure ensures that implementation details do not leak. For example, since f is pure it cannot be used to determine in what order the elements of the set are traversed. If f was impure such details could leak, e.g. by passing a function that also prints the current element, revealing the internal element order inside the set.
A higher-order function can also require that a function is impure.
For example, the definition of List.foreach requires that its function argument f is impure:
defforeach(f:a->Unit\IO,xs:List[a]):Unit\IO
The requirement that f must be impure ensures that the code makes sense: It would be meaningless to call List.foreach with a pure function since it always returns Unit.
The type and effect is sound, but not complete. That is, if a function is pure then it cannot cause an effect, whereas if a function is impure then it may, but not necessarily, cause an effect. For example, the following expression is impure even though it cannot produce an effect at run-time:
if(1==2)println("Hello World!")else()
A higher-order function can also be effect polymorphic: its effect(s) can depend on its argument(s).
For example, the standard library definition of List.map is effect polymorphic:[24]
defmap(f:a->b\e,xs:List[a]):List[b]\e
The List.map function takes a function f from elements of type a to b with effect e. The effect of the map function is itself e. Consequently, if List.map is invoked with a pure function then the entire expression is pure whereas if it is invoked with an impure function then the entire expression is impure. It is effect polymorphic.
A higher-order function that takes multiple function arguments may combine their effects.
For example, the standard library definition of forward function composition>> is pure if both its function arguments are pure:[25]
def>>(f:a->b\e1,g:b->c\e2):a->c\e1+e2=x->g(f(x))
The type and effect signature can be understood as follows: The >> function takes two function arguments: f with effect e1 and g with effect e2. The effect of >> is effect polymorphic in the conjunction of e1 and e2. If both are pure then the overall expression is pure.
The type and effect system allows arbitrary set expressions to control the purity of function arguments.
For example, it is possible to express a higher-order function h that accepts two function arguments f and g where the effects of f are disjoint from those of g:
defh(f:a->b\e1,g:b->c\e2-e1):Unit
If h is called with a function argument f which has the IO effect then g cannot have the IO effect.
The type and effect system can be used to ensure that statement expressions are useful, i.e. that if an expression or function is evaluated and its result is discarded then it must have a side-effect. For example, compiling the program fragment below:
-- Redundancy Error -------------------------------------------------->> Useless expression: It has no side-effect(s) and its result is discarded.2 | List.map(x -> 2 * x, 1 :: 2 :: Nil); ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ useless expression.
because it is non-sensical to evaluate the pure expression List.map(x -> 2 * x, 1 :: 2 :: Nil) and then to discard its result. Most likely the programmer wanted to use the result (or alternatively the expression is redundant and could be deleted). Consequently, Flix rejects such programs.
First-class datalog constraints
Flix supports Datalog programs as first-class values.[6][9][26] A Datalog program is a logic program that consists of a collection of unordered facts and rules. Together, the facts and rules imply a minimal model, a unique solution to any Datalog program. In Flix, Datalog program values can be passed to and returned from functions, stored in data structures, composed with other Datalog program values, and solved. The solution to a Datalog program (the minimal model) is itself a Datalog program. Thus, it is possible to construct pipelines of Datalog programs where the solution, i.e. "output", of one Datalog program becomes the "input" to another Datalog program.
The following edge facts define a graph:
Edge(1,2).Edge(2,3).Edge(3,4).
The following Datalog rules compute the transitive closure of the edge relation:
The local variable f holds a Datalog program value that consists of the edge facts. Similarly, the local variable p is a Datalog program value that consists of the two rules. The f <+> p expression computes the composition (i.e. union) of the two Datalog programs f and p. The solve expression computes the minimal model of the combined Datalog program, returning the edge and path facts shown above.
Since Datalog programs are first-class values, we can refactor the above program into several functions. For example:
because in p1 the type of the Edge predicate is Edge(Int32, Int32) whereas in p2 it has type Edge(String, String). The Flix compiler rejects such programs as ill-typed.
Stratified negation
The Flix compiler ensures that every Datalog program value constructed at run-time is stratified. Stratification is important because it guarantees the existence of a unique minimal model in the presence of negation. Intuitively, a Datalog program is stratified if there is no recursion through negation,[27] i.e. a predicate cannot depend negatively on itself. Given a Datalog program, a cycle detection algorithm can be used to determine if it is stratified.
For example, the following Flix program contains an expression that cannot be stratified:
defmain():#{Male(String), Husband(String), Bachelor(String)} = letp1=Husband(x):-Male(x),notBachelor(x).;letp2=Bachelor(x):-Male(x),notHusband(x).;p1<+>p2// illegal, not stratified.
because the last expression constructs a Datalog program value whose precedence graph contains a negative cycle: the Bachelor predicate negatively depends on the Husband predicate which in turn (positively) depends on the Bachelor predicate.
The Flix compiler computes the precedence graph for every Datalog program valued expression and determines its stratification at compile-time. If an expression is not stratified, the program is rejected by the compiler.
The stratification is sound, but conservative. For example, the following program is unfairly rejected:
The type system conservatively assumes that both branches of the if expression can be taken and consequently infers that there may be a negative cycle between the A and B predicates. Thus the program is rejected. This is despite the fact that at run-time the main function always returns a stratified Datalog program value.
Design philosophy
Flix is designed around a collection of stated principles:[28]
Everything is an expression. Most Flix constructs, except for top-level declarations, are expressions that evaluate to values.
Closed-world assumption. The Flix compiler assumes that the source code of the entire program is available at compile-time.
Pure and impure code is separated. The type and effect system precisely captures whether an expression may produce an effect[29]
The language has no compile-time warnings, only errors.
The principles also list several programming language features that have been deliberately omitted. In particular, Flix lacks support for:
Null values. Instead the use of the Option data type is recommended.
Implicit coercions. Instead type conversions must be performed explicitly by the programmer.
Reflection. The programmer cannot reflect over the structure of the program at run-time.
^Lucassen, J. M.; Gifford, D. K. (1988). "Polymorphic effect systems". Proceedings of the 15th ACM SIGPLAN-SIGACT symposium on Principles of programming languages - POPL '88. pp. 47–57. doi:10.1145/73560.73564. ISBN0897912527. S2CID13015611.
^Leijen, Daan (5 June 2014). "Koka: Programming with Row Polymorphic Effect Types". Electronic Proceedings in Theoretical Computer Science. 153: 100–126. arXiv:1406.2061. doi:10.4204/EPTCS.153.8. S2CID14902937.
^Madsen, Magnus; Yee, Ming-Ho; Lhoták, Ondřej (August 2016). "From Datalog to flix: a declarative language for fixed points on lattices". ACM SIGPLAN Notices. 51 (6): 194–208. doi:10.1145/2980983.2908096.
^Madsen, Magnus; Lhoták, Ondřej (2018). "Safe and sound program analysis with Flix". Proceedings of the 27th ACM SIGSOFT International Symposium on Software Testing and Analysis. pp. 38–48. doi:10.1145/3213846.3213847. ISBN9781450356992. S2CID49427988.
^Madsen, Magnus; Zarifi, Ramin; Lhoták, Ondřej (2018). "Tail call elimination and data representation for functional languages on the Java virtual machine". Proceedings of the 27th International Conference on Compiler Construction. pp. 139–150. doi:10.1145/3178372.3179499. ISBN9781450356442. S2CID3432962.
^Tauber, Tomáš; Bi, Xuan; Shi, Zhiyuan; Zhang, Weixin; Li, Huang; Zhang, Zhenrui; Oliveira, Bruno C. D. S. (2015). "Memory-Efficient Tail Calls in the JVM with Imperative Functional Objects". Programming Languages and Systems. Lecture Notes in Computer Science. Vol. 9458. pp. 11–28. doi:10.1007/978-3-319-26529-2_2. ISBN978-3-319-26528-5.
Experiment in astroparticle physics, sited at CERN in Switzerland CERN Axion Solar TelescopeRADES detector at CASTSuccessorInternational Axion ObservatoryFormationApproved on 13 April 2000Legal statusTaking data since 18 June 2003PurposeSearch for dark matter and energyHeadquartersGeneva, SwitzerlandFieldsAstroparticle physicsSpokespersonKonstantin ZioutasWebsitecast.web.cern.ch/CAST/ CAST. The telescope magnet (blue) pivots about the right-hand side, while the yellow gantry on the left of th...
Don't Phunk with My HeartSingel oleh The Black Eyed Peasdari album Monkey BusinessSisi-BBend Your BackDirilis10 Mei 2005FormatCD singel, maxi singel, unduh digitalDirekam2004GenreHip hop, R&BDurasi4:04LabelA&M, will.i.am music group, InterscopePenciptaWilliam Adams, Stacy Ferguson, Printz Board, G.Pajon Jr., Full Force, Anadi, IndewarProduserwill.i.am Don't Phunk with My Heart atau Don't Mess with My Heart pada beberapa suntingan radio, adalah sebuah lagu oleh The Black Eyed Peas dari...
Supreme Court of the United States38°53′26″N 77°00′16″W / 38.89056°N 77.00444°W / 38.89056; -77.00444EstablishedMarch 4, 1789; 235 years ago (1789-03-04)LocationWashington, D.C.Coordinates38°53′26″N 77°00′16″W / 38.89056°N 77.00444°W / 38.89056; -77.00444Composition methodPresidential nomination with Senate confirmationAuthorized byConstitution of the United States, Art. III, § 1Judge term lengthl...
Треугольное число — один из классов фигурных многоугольных чисел, определяемый как число точек, которые могут быть расставлены в форме правильного треугольника. Как видно из рисунка, n {\displaystyle n} -е треугольное число T n {\displaystyle T_{n}} — это сумма n {\displaystyle n} первых нату...
Questa voce sugli argomenti palazzi del Veneto e provincia di Verona è solo un abbozzo. Contribuisci a migliorarla secondo le convenzioni di Wikipedia. Palazzo FregosoLocalizzazioneStato Italia LocalitàGarda Coordinate45°34′33.6″N 10°42′25.34″E / 45.576°N 10.70704°E45.576; 10.70704Coordinate: 45°34′33.6″N 10°42′25.34″E / 45.576°N 10.70704°E45.576; 10.70704 Informazioni generaliCondizioniIn uso CostruzioneXV secolo Realizzazi...
Disambiguazione – Se stai cercando altri significati, vedi Maria Maddalena (disambigua). Santa Maria MaddalenaNoli me tangere di Giotto Discepola del Signore,Apostola degli apostoli NascitaMagdala, I secolo MorteEfeso/Saint-Maximin-la-Sainte-Baume[1], I secolo Venerata daTutte le Chiese che ammettono il culto dei santi Santuario principaleBasilica di Santa Maria Maddalena di Saint-Maximin-la-Sainte-Baume, Francia Ricorrenza22 luglio AttributiAmpolla d'unguento, teschio, ...
Painting by Raphael The Meeting of Leo the Great and AttilaArtistRaphaelYear1513-1514TypeFrescoDimensions500 cm × 750 cm (200 in × 300 in)LocationApostolic Palace, Vatican City The Meeting of Leo I and Attila is a fresco by the Italian Renaissance artist Raphael. It was painted from 1513 to 1514 as part of Raphael's commission to decorate the rooms that are now known as the Stanze di Raffaello, in the Apostolic Palace in the Vatican. It is located i...
Aldo Fabrizi Aldo Fabrizi, all'anagrafe Aldo Fabbrizi[1] (Roma, 1º novembre 1905 – Roma, 2 aprile 1990), è stato un attore, regista, sceneggiatore, produttore, comico e poeta italiano. Attore intenso e versatile, nel corso della sua carriera ha avuto modo di cimentarsi in ruoli sia comici sia drammatici. È stato inoltre, insieme ad Alberto Sordi e Anna Magnani, una personalità essenziale per quanto riguarda la rappresentazione della romanità nel cinema[2]. Indice 1 Biog...
Private College in Sládkovičovo, Slovakia The topic of this article may not meet Wikipedia's notability guidelines for companies and organizations. Please help to demonstrate the notability of the topic by citing reliable secondary sources that are independent of the topic and provide significant coverage of it beyond a mere trivial mention. If notability cannot be shown, the article is likely to be merged, redirected, or deleted.Find sources: Danubius University Slovakia –...
Indian actress (born 1988) Anushka SharmaSharma in 2018Born (1988-05-01) 1 May 1988 (age 36)Ayodhya, Uttar Pradesh, IndiaAlma materMount Carmel College, Bangalore (BA)OccupationActressYears active2008–presentSpouse Virat Kohli (m. 2017)Children2AwardsFull list Anushka Sharma (pronounced [əˈnʊʃka ˈʃərma]; born 1 May 1988) is an Indian actress who works in Hindi films. She has received several awards, including a Filmfare Award. One...
Result that no ranked-choice system is spoilerproof Part of the Politics seriesElectoral systems Single-winner/majoritarianPlurality First-past-the-post Plurality at-large (plurality block voting) General ticket (party block voting) Multi-round voting Two-round Exhaustive ballot Primary election Nonpartisan unified top-four Majority at-large (two-round block voting) Ranked / preferential systems Instant-runoff (alternative vote) Contingent vote Coombs' method Condorcet methods (Copeland's, Do...
Annual academic conference This article has multiple issues. Please help improve it or discuss these issues on the talk page. (Learn how and when to remove these template messages) The topic of this article may not meet Wikipedia's general notability guideline. Please help to demonstrate the notability of the topic by citing reliable secondary sources that are independent of the topic and provide significant coverage of it beyond a mere trivial mention. If notability cannot be shown, the arti...
This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: Scantic River – news · newspapers · books · scholar · JSTOR (April 2011) (Learn how and when to remove this message) River in Massachusetts and Connecticut, United States The lower Scantic River and environs, depicted on an 1892 topographic map. In Hampden, Mas...
There is a prime between any two square numbers Legendre's conjecture, proposed by Adrien-Marie Legendre, states that there is a prime number between n 2 {\displaystyle n^{2}} and ( n + 1 ) 2 {\displaystyle (n+1)^{2}} for every positive integer n {\displaystyle n} . The conjecture is one of Landau's problems (1912) on prime numbers, and is one of many open problems on the spacing of prime numbers. Unsolved problem in mathematics: Does there always exist at least one prime between n 2 {\displa...
معهد هندسة البرمجياتنوع البحثMultiprogramوظيفة700Address4500 Fifth Avenueالموقعبيتسبرغ (بنسيلفانيا)، بنسيلفانيا، الولايات المتحدة40°26′48″N 79°57′00″W / 40.4466°N 79.9500°W / 40.4466; -79.9500رموز بريد الولايات المتحدة15213AffiliationsDepartment of Defense، Department of the Armyالهيئة الإداريةجامعة كارنيغي ميلونWebsit...
СвятийОлександр І Ярославович СвятийОлександр І ЯрославовичПосмертний покров Олександра Невського, виготовлений у 1670—1680 роках у Строгановських майстернях міста Сольвичегодськ (сьогодні Архангельська область). Одне з найстаріших зображень князя що збереглося до наш...
Bua loi khai wan, bua loi dengan telur rebus manis, adalah jenis yang paling umum. Bua loi atau bua loy (bahasa Thai: บัวลอย, pengucapan [būa lɔ̄ːj], terj. har. 'lili air yang mengapung') adalah hidangan penutup Thailand. Hidangan ini terdiri dari tepung beras yang digulung menjadi bola-bola kecil, dan dimasak dengan santan dan gula.[1] Referensi ^ Templat:Cite RID
Montano Lucinocomune Montano Lucino – VedutaVeduta sul centro di Montano LocalizzazioneStato Italia Regione Lombardia Provincia Como AmministrazioneSindacoAlberto Introzzi (lista civica Insieme per Montano Lucino) dal 27-5-2019 (2º mandato) TerritorioCoordinate45°47′N 9°03′E45°47′N, 9°03′E (Montano Lucino) Altitudine400 m s.l.m. Superficie5,22 km² Abitanti5 400[1] (31-10-2023) Densità1 034,48 ab./km² FrazioniArcissa...