Control Structures

Flix — being a functional programming language — has few control-structures. Most control is simply function application. The Flix control structures are:

  • If-Then-Else: A traditional if-then-else expression.
  • Pattern Matching: A functional construct for taking apart algebraic data types.
  • Foreach: An imperative construct for iteration through collections.
  • Foreach-Yield: An imperative construct for building new collections from existing collections.
  • Monadic For-Yield: A functional construct for monadic operations, similar to Scala's for-comprehensions and Haskell's do-notation.
  • Applicative For-Yield: A functional construct for applicative operations, similar to Haskell's applicative do-notation.

What's the difference between foreach, foreach-yield, monadic forM, and applicative forA?:

The following table gives some uses cases for each construct:

ActionConstruct
Print all elements in a collection.Foreach
Apply an effectful operation to each element in a collection.Foreach
Build a new collection from existing collections.Foreach-Yield
Transform the elements of a collection.Foreach-Yield
Convert a collection of one type into another type.Foreach-Yield
Work with Options and Results.Monadic For-Yield
flatMap through a Monad.Monadic For-Yield
Work with ValidationsApplicative For-Yield

Note: Flix does not have traditional while or for-loops. Instead, we recommend the use recursion and/or one of the above constructs.