X-Git-Url: http://git.megacz.com/?a=blobdiff_plain;f=docs%2Fusers_guide%2Fglasgow_exts.xml;h=4f022395872fc81bc31e2e242cb73b22c68800f5;hb=ba00f074b38f4e168c893adc293c5b9cd6992721;hp=797a509343704bae3ede80f7d9563fc0e511aaf2;hpb=390b7c4110bc0fc9b76d6342f288d44d58fc27b9;p=ghc-hetmet.git diff --git a/docs/users_guide/glasgow_exts.xml b/docs/users_guide/glasgow_exts.xml index 797a509..4f02239 100644 --- a/docs/users_guide/glasgow_exts.xml +++ b/docs/users_guide/glasgow_exts.xml @@ -710,6 +710,202 @@ qualifier list has just one element, a boolean expression. + + + +View patterns + + + +View patterns are enabled by the flag -XViewPatterns. +More information and examples of view patterns can be found on the +Wiki +page. + + + +View patterns are somewhat like pattern guards that can be nested inside +of other patterns. They are a convenient way of pattern-matching +against values of abstract types. For example, in a programming language +implementation, we might represent the syntax of the types of the +language as follows: + + +type Typ + +data TypView = Unit + | Arrow Typ Typ + +view :: Type -> TypeView + +-- additional operations for constructing Typ's ... + + +The representation of Typ is held abstract, permitting implementations +to use a fancy representation (e.g., hash-consing to managage sharing). + +Without view patterns, using this signature a little inconvenient: + +size :: Typ -> Integer +size t = case view t of + Unit -> 1 + Arrow t1 t2 -> size t1 + size t2 + + +It is necessary to iterate the case, rather than using an equational +function definition. And the situation is even worse when the matching +against t is buried deep inside another pattern. + + + +View patterns permit calling the view function inside the pattern and +matching against the result: + +size (view -> Unit) = 1 +size (view -> Arrow t1 t2) = size t1 + size t2 + + +That is, we add a new form of pattern, written +expression -> +pattern that means "apply the expression to +whatever we're trying to match against, and then match the result of +that application against the pattern". The expression can be any Haskell +expression of function type, and view patterns can be used wherever +patterns are used. + + + +The semantics of a pattern ( +exp -> +pat ) are as follows: + + + + Scoping: + +The variables bound by the view pattern are the variables bound by +pat. + + + +Any variables in exp are bound occurrences, +but variables bound "to the left" in a pattern are in scope. This +feature permits, for example, one argument to a function to be used in +the view of another argument. For example, the function +clunky from can be +written using view patterns as follows: + + +clunky env (lookup env -> Just val1) (lookup env -> Just val2) = val1 + val2 +...other equations for clunky... + + + + +More precisely, the scoping rules are: + + + +In a single pattern, variables bound by patterns to the left of a view +pattern expression are in scope. For example: + +example :: Maybe ((String -> Integer,Integer), String) -> Bool +example Just ((f,_), f -> 4) = True + + +Additionally, in function definitions, variables bound by matching earlier curried +arguments may be used in view pattern expressions in later arguments: + +example :: (String -> Integer) -> String -> Bool +example f (f -> 4) = True + +That is, the scoping is the same as it would be if the curried arguments +were collected into a tuple. + + + + + +In mutually recursive bindings, such as let, +where, or the top level, view patterns in one +declaration may not mention variables bound by other declarations. That +is, each declaration must be self-contained. For example, the following +program is not allowed: + +let {(x -> y) = e1 ; + (y -> x) = e2 } in x + + +(We may lift this +restriction in the future; the only cost is that type checking patterns +would get a little more complicated.) + + + + + + + + + + Typing: If exp has type +T1 -> +T2 and pat matches +a T2, then the whole view pattern matches a +T1. + + + Matching: To the equations in Section 3.17.3 of the +Haskell 98 +Report, add the following: + +case v of { (e -> p) -> e1 ; _ -> e2 } + = +case (e v) of { p -> e1 ; _ -> e2 } + +That is, to match a variable v against a pattern +( exp +-> pat +), evaluate ( +exp v +) and match the result against +pat. + + + Efficiency: When the same view function is applied in +multiple branches of a function definition or a case expression (e.g., +in size above), GHC makes an attempt to collect these +applications into a single nested case expression, so that the view +function is only applied once. Pattern compilation in GHC follows the +matrix algorithm described in Chapter 4 of The +Implementation of Functional Programming Languages. When the +top rows of the first column of a matrix are all view patterns with the +"same" expression, these patterns are transformed into a single nested +case. This includes, for example, adjacent view patterns that line up +in a tuple, as in + +f ((view -> A, p1), p2) = e1 +f ((view -> B, p3), p4) = e2 + + + + The current notion of when two view pattern expressions are "the +same" is very restricted: it is not even full syntactic equality. +However, it does include variables, literals, applications, and tuples; +e.g., two instances of view ("hi", "there") will be +collected. However, the current implementation does not compare up to +alpha-equivalence, so two instances of (x, view x -> +y) will not be coalesced. + + + + + + + + + @@ -863,10 +1059,11 @@ This name is not supported by GHC. + + Rebindable syntax - GHC allows most kinds of built-in syntax to be rebound by the user, to facilitate replacing the Prelude with a home-grown version, for example. @@ -955,16 +1152,16 @@ GHC allows a small extension to the syntax of left operator sections, which allows you to define postfix operators. The extension is this: the left section (e !) - + is equivalent (from the point of view of both type checking and execution) to the expression ((!) e) - + (for any expression e and operator (!). The strict Haskell 98 interpretation is that the section is equivalent to (\y -> (!) e y) - + That is, the operator must be a function of two arguments. GHC allows it to take only one argument, and that in turn allows you to write the function postfix. @@ -1020,6 +1217,170 @@ This reduces the clutter of qualified names when you import two records from different modules that use the same field name. + + + + +Record puns + + + +Record puns are enabled by the flag -XRecordPuns. + + + +When using records, it is common to write a pattern that binds a +variable with the same name as a record field, such as: + + +data C = C {a :: Int} +f (C {a = a}) = a + + + + +Record punning permits the variable name to be elided, so one can simply +write + + +f (C {a}) = a + + +to mean the same pattern as above. That is, in a record pattern, the +pattern a expands into the pattern a = +a for the same name a. + + + +Note that puns and other patterns can be mixed in the same record: + +data C = C {a :: Int, b :: Int} +f (C {a, b = 4}) = a + +and that puns can be used wherever record patterns occur (e.g. in +let bindings or at the top-level). + + + +Record punning can also be used in an expression, writing, for example, + +let a = 1 in C {a} + +instead of + +let a = 1 in C {a = a} + + +Note that this expansion is purely syntactic, so the record pun +expression refers to the nearest enclosing variable that is spelled the +same as the field name. + + + + + + + +Record wildcards + + + +Record wildcards are enabled by the flag -XRecordWildCards. + + + +For records with many fields, it can be tiresome to write out each field +individually in a record pattern, as in + +data C = C {a :: Int, b :: Int, c :: Int, d :: Int} +f (C {a = 1, b = b, c = c, d = d}) = b + c + d + + + + +Record wildcard syntax permits a (..) in a record +pattern, where each elided field f is replaced by the +pattern f = f. For example, the above pattern can be +written as + +f (C {a = 1, ..}) = b + c + d + + + + +Note that wildcards can be mixed with other patterns, including puns +(); for example, in a pattern C {a += 1, b, ..}). Additionally, record wildcards can be used +wherever record patterns occur, including in let +bindings and at the top-level. For example, the top-level binding + +C {a = 1, ..} = e + +defines b, c, and +d. + + + +Record wildcards can also be used in expressions, writing, for example, + + +let {a = 1; b = 2; c = 3; d = 4} in C {..} + + +in place of + + +let {a = 1; b = 2; c = 3; d = 4} in C {a=a, b=b, c=c, d=d} + + +Note that this expansion is purely syntactic, so the record wildcard +expression refers to the nearest enclosing variables that are spelled +the same as the omitted field names. + + + + + + + +Local Fixity Declarations + + +A careful reading of the Haskell 98 Report reveals that fixity +declarations (infix, infixl, and +infixr) are permitted to appear inside local bindings +such those introduced by let and +where. However, the Haskell Report does not specify +the semantics of such bindings very precisely. + + +In GHC, a fixity declaration may accompany a local binding: + +let f = ... + infixr 3 `f` +in + ... + +and the fixity declaration applies wherever the binding is in scope. +For example, in a let, it applies in the right-hand +sides of other let-bindings and the body of the +letC. Or, in recursive do +expressions (), the local fixity +declarations of aA let statement scope over other +statements in the group, just as the bound name does. + + +Moreover, a local fixity declatation *must* accompany a local binding of +that name: it is not possible to revise the fixity of name bound +elsewhere, as in + +let infixr 9 $ in ... + + +Because local fixity declarations are technically Haskell 98, no flag is +necessary to enable them. + + @@ -1383,11 +1744,6 @@ dictionaries for Eq and Show respectively, extract it on pattern matching. - -Notice the way that the syntax fits smoothly with that used for -universal quantification earlier. - - @@ -1660,9 +2016,9 @@ In the example, the equality dictionary is used to satisfy the equality constrai generated by the call to elem, so that the type of insert itself has no Eq constraint. -This behaviour contrasts with Haskell 98's peculiar treament of +This behaviour contrasts with Haskell 98's peculiar treatment of contexts on a data type declaration (Section 4.2.1 of the Haskell 98 Report). -In Haskell 98 the defintion +In Haskell 98 the definition data Eq a => Set' a = MkSet' [a] @@ -1771,7 +2127,7 @@ field f must be the same (modulo alpha conversion). At the moment, record updates are not yet possible with GADT-style declarations, so support is limited to record construction, selection and pattern matching. -For exmaple +For example aPerson = Adult { name = "Fred", children = [] } @@ -1878,7 +2234,7 @@ constructor). You cannot use a deriving clause for a GADT; only for -an ordianary data type. +an ordinary data type. @@ -1946,7 +2302,7 @@ The third is not Haskell 98, and risks losing termination of instances. GHC takes a conservative position: it accepts the first two, but not the third. The rule is this: each constraint in the inferred instance context must consist only of type variables, -with no repititions. +with no repetitions. This rule is applied regardless of flags. If you want a more exotic context, you can write @@ -1982,7 +2338,7 @@ For example: deriving instance MonadState Int Foo GHC always treats the last parameter of the instance -(Foo in this exmample) as the type whose instance is being derived. +(Foo in this example) as the type whose instance is being derived. @@ -2032,14 +2388,14 @@ Haskell 98, you can inherit instances of Eq, Ord + newtype Dollars = Dollars Int - + and you want to use arithmetic on Dollars, you have to explicitly define an instance of Num: - + instance Num Dollars where Dollars a + Dollars b = Dollars (a+b) ... @@ -2057,17 +2413,17 @@ dictionary, only slower! GHC now permits such instances to be derived instead, using the flag , so one can write - + newtype Dollars = Dollars Int deriving (Eq,Show,Num) - + and the implementation uses the same Num dictionary for Dollars as for Int. Notionally, the compiler derives an instance declaration of the form - + instance Num Int => Num Dollars - + which just adds or removes the newtype constructor according to the type. @@ -2077,27 +2433,27 @@ We can also derive instances of constructor classes in a similar way. For example, suppose we have implemented state and failure monad transformers, such that - + instance Monad m => Monad (State s m) instance Monad m => Monad (Failure m) - + In Haskell 98, we can define a parsing monad by - + type Parser tok m a = State [tok] (Failure m) a - + which is automatically a monad thanks to the instance declarations above. With the extension, we can make the parser type abstract, without needing to write an instance of class Monad, via - + newtype Parser tok m a = Parser (State [tok] (Failure m) a) deriving Monad In this case the derived instance declaration is of the form - + instance Monad (State [tok] (Failure m)) => Monad (Parser tok m) - + Notice that, since Monad is a constructor class, the instance is a partial application of the new type, not the @@ -2112,12 +2468,12 @@ newtype is the last class parameter. In this case, a ``partial application'' of the class appears in the deriving clause. For example, given the class - + class StateMonad s m | m -> s where ... instance Monad m => StateMonad s (State s m) where ... - + then we can derive an instance of StateMonad for Parsers by - + newtype Parser tok m a = Parser (State [tok] (Failure m) a) deriving (Monad, StateMonad [tok]) @@ -2125,7 +2481,7 @@ then we can derive an instance of StateMonad for Par The derived instance is obtained by completing the application of the class to the new type: - + instance StateMonad [tok] (State [tok] (Failure m)) => StateMonad [tok] (Parser tok m) @@ -2145,9 +2501,9 @@ the newtype and its representation. Derived instance declarations are constructed as follows. Consider the declaration (after expansion of any type synonyms) - + newtype T v1...vn = T' (t vk+1...vn) deriving (c1...cm) - + where @@ -2176,17 +2532,17 @@ where Then, for each ci, the derived instance declaration is: - + instance ci t => ci (T v1...vk) As an example which does not work, consider - + newtype NonMonad m s = NonMonad (State s m s) deriving Monad - + Here we cannot derive the instance - + instance Monad (State s m) => Monad (NonMonad m) - + because the type variable s occurs in State s m, and so cannot be "eta-converted" away. It is a good thing that this @@ -2200,7 +2556,7 @@ Notice also that the order of class parameters becomes important, since we can only derive instances for the last one. If the StateMonad class above were instead defined as - + class StateMonad m s | m -> s where ... @@ -2788,7 +3144,7 @@ typechecker loop: class F a b | a->b instance F [a] [[a]] instance (D c, F a c) => D [a] -- 'c' is not mentioned in the head - + Similarly, it can be tempting to lift the coverage condition: class Mul a b c | a b -> c where @@ -2898,7 +3254,7 @@ by which time more is known about the type b. The willingness to be overlapped or incoherent is a property of the instance declaration itself, controlled by the presence or otherwise of the -and flags when that mdodule is +and flags when that module is being defined. Neither flag is required in a module that imports and uses the instance declaration. Specifically, during the lookup process: @@ -3011,7 +3367,7 @@ instance IsString [Char] where fromString cs = cs The class IsString is not in scope by default. If you want to mention -it explicitly (for exmaple, to give an instance declaration for it), you can import it +it explicitly (for example, to give an instance declaration for it), you can import it from module GHC.Exts. @@ -3192,7 +3548,7 @@ J Lewis, MB Shields, E Meijer, J Launchbury, Boston, Jan 2000. -(Most of the following, stil rather incomplete, documentation is +(Most of the following, still rather incomplete, documentation is due to Jeff Lewis.) Implicit parameter support is enabled with the option @@ -3372,7 +3728,7 @@ In the former case, len_acc1 is monomorphic in its own right-hand side, so the implicit parameter ?acc is not passed to the recursive call. In the latter case, because len_acc2 has a type signature, the recursive call is made to the -polymoprhic version, which takes ?acc +polymorphic version, which takes ?acc as an implicit parameter. So we get the following results in GHCi: Prog> len1 "hello" @@ -3497,7 +3853,7 @@ Other points: '?x' and '%x' are entirely distinct implicit parameters: you - can use them together and they won't intefere with each other. + can use them together and they won't interfere with each other. You can bind linear implicit parameters in 'with' clauses. @@ -4010,7 +4366,7 @@ a type. (This is a change from GHC's earlier design.) Furthermore, distinct lexical type variables stand for distinct type variables. This means that every programmer-written type signature -(includin one that contains free scoped type variables) denotes a +(including one that contains free scoped type variables) denotes a rigid type; that is, the type is fully known to the type checker, and no inference is involved. Lexical type variables may be alpha-renamed freely, without @@ -4027,7 +4383,7 @@ A lexically scoped type variable can be bound by: -In Haskell, a programmer-written type signature is implicitly quantifed over +In Haskell, a programmer-written type signature is implicitly quantified over its free type variables (Section 4.1.2 @@ -4094,7 +4450,7 @@ type variable s into scope, in the annotated expression Pattern type signatures A type signature may occur in any pattern; this is a pattern type -signature. +signature. For example: -- f and g assume that 'a' is already in scope @@ -4102,14 +4458,32 @@ For example: g (x::a) = x h ((x,y) :: (Int,Bool)) = (y,x) -In the case where all the type variables in the pattern type sigature are +In the case where all the type variables in the pattern type signature are already in scope (i.e. bound by the enclosing context), matters are simple: the signature simply constrains the type of the pattern in the obvious way. -There is only one situation in which you can write a pattern type signature that -mentions a type variable that is not already in scope, namely in pattern match -of an existential data constructor. For example: +Unlike expression and declaration type signatures, pattern type signatures are not implictly generalised. +The pattern in a patterm binding may only mention type variables +that are already in scope. For example: + + f :: forall a. [a] -> (Int, [a]) + f xs = (n, zs) + where + (ys::[a], n) = (reverse xs, length xs) -- OK + zs::[a] = xs ++ ys -- OK + + Just (v::b) = ... -- Not OK; b is not in scope + +Here, the pattern signatures for ys and zs +are fine, but the one for v is not because b is +not in scope. + + +However, in all patterns other than pattern bindings, a pattern +type signature may mention a type variable that is not in scope; in this case, +the signature brings that type variable into scope. +This is particularly important for existential data constructors. For example: data T = forall a. MkT [a] @@ -4119,16 +4493,21 @@ of an existential data constructor. For example: t3::[a] = [t,t,t] Here, the pattern type signature (t::a) mentions a lexical type -variable that is not already in scope. Indeed, it cannot already be in scope, +variable that is not already in scope. Indeed, it cannot already be in scope, because it is bound by the pattern match. GHC's rule is that in this situation (and only then), a pattern type signature can mention a type variable that is not already in scope; the effect is to bring it into scope, standing for the existentially-bound type variable. -If this seems a little odd, we think so too. But we must have +When a pattern type signature binds a type variable in this way, GHC insists that the +type variable is bound to a rigid, or fully-known, type variable. +This means that any user-written type signature always stands for a completely known type. + + +If all this seems a little odd, we think so too. But we must have some way to bring such type variables into scope, else we -could not name existentially-bound type variables in subequent type signatures. +could not name existentially-bound type variables in subsequent type signatures. This is (now) the only situation in which a pattern type @@ -4253,12 +4632,12 @@ This is rejected by Haskell 98, but under Jones's scheme the definition for g is typechecked first, separately from that for f, because the reference to f in g's right -hand side is ingored by the dependency analysis. Then g's +hand side is ignored by the dependency analysis. Then g's type is generalised, to get g :: Ord a => a -> Bool -Now, the defintion for f is typechecked, with this type for +Now, the definition for f is typechecked, with this type for g in the type environment. @@ -4549,7 +4928,7 @@ The basic idea is to compile the program twice: Then compile it again with , and additionally use - to name the object files differentliy (you can choose any suffix + to name the object files differently (you can choose any suffix that isn't the normal object suffix here). GHC will automatically load the object files built in the first step when executing splice expressions. If you omit the flag when @@ -5107,7 +5486,7 @@ g6 x = case f x of { y -> body } g7 x = case f x of { !y -> body } The functions g5 and g6 mean exactly the same thing. -But g7 evalutes (f x), binds y to the +But g7 evaluates (f x), binds y to the result, and then evaluates body. Bang patterns work in let and where @@ -5420,7 +5799,7 @@ Assertion failures can be caught, see the documentation for the When you compile any module that imports and uses any of the specified entities, GHC will print the specified message. - You can only depecate entities declared at top level in the module + You can only deprecate entities declared at top level in the module being compiled, and you can only use unqualified names in the list of entities being deprecated. A capitalised name, such as T refers to either the type constructor T @@ -5479,8 +5858,26 @@ key_function :: Int -> String -> (Bool, Double) The major effect of an INLINE pragma is to declare a function's “cost” to be very low. The normal unfolding machinery will then be very keen to - inline it. - + inline it. However, an INLINE pragma for a + function "f" has a number of other effects: + + +No funtions are inlined into f. Otherwise +GHC might inline a big function into f's right hand side, +making f big; and then inline f blindly. + + +The float-in, float-out, and common-sub-expression transformations are not +applied to the body of f. + + +An INLINE function is not worker/wrappered by strictness analysis. +It's going to be inlined wholesale instead. + + +All of these effects are aimed at ensuring that what gets inlined is +exactly what you asked for, no more and no less. + Syntactically, an INLINE pragma for a function can be put anywhere its type signature could be put. @@ -5652,7 +6049,7 @@ happen. {-# SPECIALIZE f :: <type> #-} - is valid if and only if the defintion + is valid if and only if the definition f_spec :: <type> f_spec = f @@ -5668,7 +6065,7 @@ happen. h :: Eq a => a -> a -> a {-# SPECIALISE h :: (Eq a) => [a] -> [a] -> [a] #-} - + The last of these examples will generate a RULE with a somewhat-complex left-hand side (try it yourself), so it might not fire very well. If you use this kind of specialisation, let us know how well it works. @@ -5677,7 +6074,7 @@ well. If you use this kind of specialisation, let us know how well it works. A SPECIALIZE pragma can optionally be followed with a INLINE or NOINLINE pragma, optionally followed by a phase, as described in . -The INLINE pragma affects the specialised verison of the +The INLINE pragma affects the specialised version of the function (only), and applies even if the function is recursive. The motivating example is this: @@ -6373,7 +6770,7 @@ If you add you get a more detailed listing. - The definition of (say) build in GHC/Base.lhs looks llike this: + The definition of (say) build in GHC/Base.lhs looks like this: build :: forall a. (forall b. (a -> b -> b) -> b -> b) -> [a] @@ -6470,7 +6867,7 @@ r) -> Special built-in functions -GHC has a few built-in funcions with special behaviour. These +GHC has a few built-in functions with special behaviour. These are now described in the module GHC.Prim in the library documentation. @@ -6640,7 +7037,7 @@ So this too is illegal: op2 :: a -> Bool op2 {| p :*: q |} (x :*: y) = False -(The reason for this restriction is that we gather all the equations for a particular type consructor +(The reason for this restriction is that we gather all the equations for a particular type constructor into a single generic instance declaration.) @@ -6671,7 +7068,7 @@ Here, op1, op2, op3 are OK, but op4 is rejected, because it has a type variable inside a list. -This restriction is an implementation restriction: we just havn't got around to +This restriction is an implementation restriction: we just haven't got around to implementing the necessary bidirectional maps over arbitrary type constructors. It would be relatively easy to add specific type constructors, such as Maybe and list, to the ones that are allowed.