Differences to Haskell base
Moggi looks like Haskell and ports the API of Haskell’s base library, but it is a
strict language that compiles to three hosts (PHP, the JVM, .NET) — not to
native code through the C ABI. This page tells you, as a Haskell programmer,
what will surprise you. Everything not mentioned here is meant to behave like
base; if you find a divergence that is not listed, that is a bug — please
report it.
Two of them show up in the first five minutes of any port, and both are
below: evaluation is strict, and String is the host’s own string type
rather than [Char]. Most of what follows is a consequence of the first.
New to Moggi? Start with the tour instead; this page assumes you already know Haskell. The language itself is described in the language reference, and host calls in the FFI guide.
Evaluation is strict
This is the one big difference, and most of the rest follows from it. Arguments are evaluated before a call; nothing is deferred to first use — not function arguments, not record fields, not constructor fields.
- There are no thunks, no
seq, no$!, and no bang patterns. They would have no work to do. - There are no infinite or self-referential structures.
ones = 1 : onescannot be expressed, and for the same reasoniterate,repeat, andcycleare not provided — on lists or onNonEmpty. In a strict language each of them would diverge while looking like the valuebasepromises, so they are left out on purpose rather than shipped broken. - Folds come in one strict flavour each.
foldlandfoldrevaluate as they go and there is nofoldl';foldis the monoidal fold (t m -> m, thefoldMaprole). There is noData.Map.Strictbeside a lazyData.Map— the containers package’sData.Mapis strict, full stop. - Partial application is still a value you can pass around; it just holds already-evaluated arguments instead of a suspended computation.
- Fixed points have to be tied to a value that exists, not to a thunk.
fixis the strict fixed point ofData.Function, andmfix frunsfonce with a reference to its own result: recursion through that reference is ordinary recursion once the result is there, and reading it earlier raises anErrorCallinstead of looping or answering a placeholder. So the value you recurse into must be buildable without being forced — a function is the usual shape,mfix (\rec -> pure (\n -> … rec (n - 1))), and an argument that is never demanded also works.MonadFixhas instances forIO,Identity,Maybe,Either eandDown, andfixIO,unsafeFixIOandControl.Arrow’sloopfor(->)behave the same way.
Strings and characters
String is a host-native string (UTF-8/UTF-16 depending on the backend), not
[Char]. Char is a Unicode scalar value. Consequences:
- There is
Data.Stringbut noData.Text. To move between the two worlds,Data.Stringprovidespack,unpack, andsingleton. Data.Stringalso provideslength,take,drop,isPrefixOf, andisSuffixOffor strings, and path manipulation (System.FilePath,System.Directory) works directly on those strings:FilePathisString, not[Char]. There is noOsPath/OsStringlayer and no encoding step — pure path functions only ever inspect ASCII (separators, drive letters, extension markers) and pass everything else through untouched, and host calls take the string as-is.- A module importing both
Data.StringandData.Listmust disambiguate those names with ahidinglist.
Names that differ
A few names are deliberately different, because Moggi is not a Haskell source-compatibility target and keeps one spelling per operation:
- The
Functormethod ismap, and it is also the only mapping function — there is nofmap, andData.Listdeclares nomapof its own.(<$>),(<$),(<$)’s companions, and(<&>)all exist with their usual meanings. Monadhas noreturn. Usepure, whichbaseitself saysreturnshould equal.Monoidlikewise has nomappend:(<>)is the only spelling, asbaserecommends.- List literals are context-directed. When the expected type has an
IsListinstance,[1, 2]is built withfromList; with no such expectation it is an ordinary[a]. There is no language extension to enable: the class lives inMoggi.IsListand the syntax is always available. Alternative’ssomeandmanyare class methods with defaults (as inbase), so an instance with a faster repetition strategy can override them.
Records
Field access uses projection: person.name, which binds tighter than function
application, as . does in the host languages. A record declaration generates
no selector function, so two records in one module can freely share field names
— the receiver’s type selects the field, and there is no name person spelling.
This is what DuplicateRecordFields and OverloadedRecordDot give you there,
always on here.
Record update (p { age = 31 }, nested form included) works on record types
with a single constructor and is spelled as it is there, without
OverloadedRecordUpdate or RebindableSyntax. A multi-constructor type cannot be updated, because
which fields the value has is only known at run time; matching on the
constructor explicitly is the alternative (see
language.md § Records).
Numbers
Intis 64-bit signed on every backend (a 64-bit PHP build is required).Integeris arbitrary precision, as inbase.- The only floating-point type is
Double; there is noFloat.Real,RealFrac, andRealFloatare classes, as inbase, andDoubleis their only instance. - An ambiguous numeric variable defaults to
Intfirst, thenDouble—default (Int, Double)wherebasehas(Integer, Double). An unannotated computation that overflowsIntwraps instead of promoting, so annotateIntegerwhere the range matters.
The Prelude is smaller
The Prelude re-exports the pure core plus the System.IO essentials
(IO, FilePath, putChar, putStr, putStrLn, print, getChar,
getLine, getContents, interact, readFile, writeFile, appendFile,
readIO, readLn, IOError, ioError, userError). Beyond those, handles
come from import System.IO, paths from import System.FilePath, and
directories from import System.Directory.
Exceptions
The synchronous base-4.22 API is available, including typed handlers,
ExceptionContext, annotations, and the masking names. The differences that
matter are:
- No asynchronous delivery:
throwToandkillThreadonly target the calling thread, and masking is a no-op (getMaskingStateis alwaysUnmasked). Exceptionrequires(Typeable, Show).Typeableis synthesized, so a normal exception only needsShow;SomeExceptionis a pattern synonym but still constructs and matches as expected.Control.Exception.Backtraceis not available.HasCallStackworks.error,throw,throwIO, andioErrorreport the host stack at the raise site;errorWithoutStackTraceomits it. The API is inMoggi.Stack/Moggi.Stack.Types, and the stack is a snapshot rather than a solver-grown allocation stack (whoCreatedhas no allocation stack).mapExceptionis the identity because its argument is already evaluated.- Host failures are
HostExceptionfromMoggi.IO.Exception;Control.Exceptiondoes not re-export it.System.IOstill translates file errors toIOException. ExceptionAnnotationinstances must writedisplayExceptionAnnotation; there are no default signatures.
Concurrency
Control.Concurrent and the MVar, Chan, QSem, and QSemN modules are
available. forkIO creates an OS thread, not a green thread; forked threads
are daemons and do not keep the process alive after main. A blocking foreign
call blocks only the thread that makes it.
- Async exceptions cannot cross threads;
throwTo/killThreadonly target the caller, and masking is a no-op. - Capabilities are fixed at one:
forkOnignores its argument,getNumCapabilitiesis1,setNumCapabilitieshas no effect, andforkOSisforkIO. threadWaitRead,threadWaitWrite, and their STM forms raise an unsupported operation error: there is no descriptor readiness or STM.getChanContentsis strict: it drains the values queued at the call and returns[]when empty; usereadChanin a loop for a live stream.- PHP needs ZTS and
ext-parallel, with no single-threaded fallback. A forked action is copied by value, so captures must be serializable: ordinary data andMVar/Chanvalues work; host handles and nested closures do not.
Calling the host
base reaches the host through the C FFI; Moggi declares host members
directly with foreign declarations (see the FFI guide):
- A declaration belongs to exactly one backend, chosen at compile time. Shared
code keeps the portable surface in a facade module and puts each backend’s
declarations in an implementation module behind it
(
System.IO→System.IO.PHP/System.IO.JVM/System.IO.DotNet). - A declaration is checked against the host wherever the host can be asked at
compile time: a missing member, a wrong member kind or a wrong descriptor is
a compile error. What the check cannot promise is the host’s behaviour, so
a failure at run time still arrives as
HostException. - There is no
Foreign.*layer: no pointers, noStorable, no manual marshalling. In result positionMaybe,Either, lists, andHandleare converted from the host value; in argument position Moggi’s own representations are refused rather than passed to the host. - One PHP-only special case: PHP’s
mixedis not a class, so aforeign phpdeclaration may name it as a type, andPlatform.PHP’sPHPValuereifies such a value into a matchable ADT. The JVM and .NET need no equivalent (java.lang.Object,System.Object).
Where things live
Haskell’s base splits its definitions across a ghc-internal package behind
re-export shims; Moggi does not mirror that tree. Implementations live in the
module you import: numbers in Data.Int/Data.Word/Data.Integer/
Data.Double/Data.Num/Data.Real, Show and Read directly in
Text.Show/Text.Read. Data.Tuple additionally carries the tuple types
base puts in its internal tuple module (Solo, Tuple0–Tuple64, Unit),
so there is no separate internal layer to learn.
Because there is one file per module and no build file, each library lives
where you import it — there is no separate .cabal package tree to learn.
What is missing
No public module is a placeholder: a module either exists with base’s API or
is absent, and the standard library page lists
what is absent, so a name you cannot bring into scope is simply not there. A few
operations whose host machinery does not exist are still present with their
base signatures and report the missing capability when called, as described
under Concurrency and Exceptions. What shapes a
port is not a missing function but the language:
Float has no counterpart (Numbers), IO does not nest, so
MonadIO has only its IO instance (see the
purity boundary), and the lazy shapes
listed above — ZipList, unsafeInterleaveIO, iterate, mfix on lists —
cannot be expressed at all. Debug.Trace’s eventlog and marker functions are
no-ops, and traceStack prints host frames where base would print profiling
annotations.
No language extensions to enable
There are no {-# LANGUAGE … #-} opt-ins for features. Everything the compiler
implements — multi-parameter classes and their associated types, higher-kinded
types, type-level data, generic programming — is available in every module; no
feature is switched on per module or per file. The only LANGUAGE pragma is
{-# LANGUAGE NoImplicitPrelude #-}, which drops the implicit Prelude
import. A module can also carry a {-# BACKEND … #-} pragma above its header
(language.md § Pragmas).
So a program ported here does not need its pragmas translated, and there is no way to disable a feature to get different behaviour: a feature either exists, with one behaviour, or it does not exist at all.
Extensions that are simply on
The list is what has a counterpart, not what exists; each row names the pragma you would write there and the syntax that works here with no pragma at all.
| Extension | What is available in every module |
|---|---|
MultiParamTypeClasses |
class Convert a b where convert :: a -> b |
FlexibleInstances |
instance C (Pair Int b) — an instance head may be a partially applied type |
FlexibleContexts |
f :: Eq [a] => [a] -> Bool |
ConstrainedClassMethods |
class C a where c :: Eq a => a -> a -> Bool |
TypeFamilies |
associated types (class Collection c where type Element c) and closed families declared on their own (type family Not (x :: Bool) where) |
KindSignatures |
data Tagged (c :: Color) = Tagged |
RoleAnnotations |
type role T phantom representational |
DataKinds |
promoted constructors ('Red), Nat, Symbol |
DuplicateRecordFields |
two records may both declare name |
OverloadedRecordDot |
person.name, chained |
OverloadedRecordUpdate |
p { age = 31 }, nested included |
DeriveFunctor, DeriveFoldable, DeriveTraversable |
deriving (Functor, Foldable, Traversable) |
DeriveGeneric |
deriving (Generic) with import Moggi.Generics |
GeneralizedNewtypeDeriving |
deriving newtype (Num) |
DeriveAnyClass |
deriving anyclass (C) |
DerivingVia |
deriving via (V) C |
DerivingStrategies |
deriving stock (C), deriving newtype (C), deriving anyclass (C), deriving via (V) C |
StandaloneDeriving |
deriving instance (Eq a) => Eq (T a) |
GADTs |
data Expr a where Lit :: Int -> Expr Int; with it, existential constructor variables (MkBox :: a -> Box) and refinement from a constructor’s written result type |
BlockArguments |
when True do …, with no $ |
The reverse has no analogue: an extension with nothing behind it has no pragma
either. GADTs is the one readers look for first, and it is part of the
language: data Expr a where … parses, refines and runs like it does in
Haskell (data types).
What is not different
These look like deviations when diffing against base, and are not:
ArithException’s constructors andShowstrings,ErrorCall’sShow, andbitSizefailing onInteger.- Operator fixities and precedence in
Data.Bits,Data.Function, andData.List. Data.Bits’s class split (Bits,FiniteBits) and the two’s-complement behaviour for negativeIntegervalues.Intbeing 64-bit, which is the width it has on a 64-bit platform.