https://wiki.haskell.org/api.php?action=feedcontributions&user=Briqueabraque&feedformat=atomHaskellWiki - User contributions [en]2024-03-29T04:42:12ZUser contributionsMediaWiki 1.35.5https://wiki.haskell.org/index.php?title=FFI_cook_book&diff=24186FFI cook book2008-11-21T10:34:56Z<p>Briqueabraque: </p>
<hr />
<div>This attempts to be a guide/tutorial/cookbook approach<br />
to writing a library using external (FFI) functions.<br />
Some people complain that cookbook approaches encourage a lack of thinking;<br />
that may be so, but they also help novices get started faster.<br />
Being a little hard of thinking myself, I would have been grateful<br />
for something like this when I was getting started.<br />
The FFI spec, while valuable, is not a tutorial.<br />
<br />
This guide contains examples and lessons accumulated writing an FFI binding<br />
to the Oracle DBMS OCI (Oracle Call Interface), a low-level C library.<br />
<br />
My FFI library code tends to look like imperative code written in Haskell.<br />
I guess we should expect this to some extent when dealing with external libraries,<br />
although it might be better (for me) to explore more functional alternatives.<br />
(However, Haskell also seems to be quite a good language<br />
for writing imperative code in.)<br />
<br />
-- AlistairBayley<br />
<br />
These libraries are useful for memory management, and using C pointers.<br />
<br />
Contains peek, poke, peekByteOff, pokeByteOff, etc:<br />
http://www.haskell.org/ghc/docs/latest/html/libraries/base/Foreign-Storable.html<br />
<br />
Contains alloca, malloc, free, etc:<br />
<br />
http://www.haskell.org/ghc/docs/latest/html/libraries/base/Foreign-Marshal-Alloc.html<br />
<br />
== Calling C functions ==<br />
<br />
=== Passing opaque structures/types ===<br />
<br />
'''Problem:'''<br />
A C function creates an opaque structure,<br />
which I must later pass to other C functions.<br />
What type should I use?<br />
<br />
'''Solution:'''<br />
Create a datatype to represent the opaque structure.<br />
Note that the C functions expect a pointer to the structure,<br />
so I've created a type synonym called OCIHandle for these.<br />
<br />
<haskell><br />
> data OCIStruct = OCIStruct<br />
> type OCIHandle = Ptr OCIStruct<br />
<br />
GHC allows this constructor-less version (with -fglasgow-exts):<br />
<br />
> data OCIStruct<br />
</haskell><br />
<br />
''this would also work, if only for the lesser lines of code you'd need to type:''<br />
<haskell><br />
--no need for the data declaration<br />
type OCIStruct = Ptr ()<br />
</haskell><br />
''i don't know if there are any side effects to this but it works fine for me so far'' -- eyan at eyan dot org<br />
<br />
The side-effect I wanted to avoid was using the wrong pointer at the wrong time. Consider:<br />
<br />
<haskell><br />
type EnvStruct = Ptr ()<br />
type EnvHandle = Ptr EnvStruct<br />
type ErrorStruct = Ptr ()<br />
type ErrorHandle = Ptr ErrorStruct<br />
</haskell><br />
<br />
ErrorHandle and EnvHandle have the same type i.e. you can use one where you would use the other. I would rather use different datatypes so the compiler can help me catch these type errors. Better would be:<br />
<br />
<haskell><br />
data EnvStruct = EnvStruct<br />
type EnvHandle = Ptr EnvStruct<br />
data ErrorStruct = ErrorStruct<br />
type ErrorHandle = Ptr ErrorStruct<br />
</haskell><br />
<br />
-- AlistairBayley<br />
<br />
''You can also use something like Ptr a when functions expect void*, and use that to enforce type consistency. For instance, you have a function that expects a pointer to a buffer and returns the old one:''<br />
<br />
<haskell><br />
foreign import ccall "name_of_function" function<br />
:: Ptr a -> IO (Ptr a)<br />
</haskell><br />
<br />
=== Passing pointer-to-pointer-to-thing ===<br />
<br />
'''Problem:'''<br />
C function takes a pointer-to-a-pointer argument,<br />
which is modified to point to some newly allocated structure or value.<br />
The return value of the C function is a success-or-failure code (int).<br />
So we effectively have parameters which are in-out.<br />
How do you wrap these in Haskell functions that return the actual structure<br />
(and raise an exception on failure)?<br />
<br />
'''Solutions:'''<br />
<br />
==== Single argument case ====<br />
<br />
If the function only modifies one of its arguments, then use code like this:<br />
<br />
<haskell><br />
OCIHandle is a synonym for Ptr OCIStruct, so the second argument to <br />
OCIHandleAlloc has type Ptr Ptr OCIStruct. The C signature for OCIHandleAlloc<br />
describes the second argument as **void, i.e. a pointer to a pointer to something.<br />
<br />
> foreign import ccall "oci.h OCIHandleAlloc" ociHandleAlloc ::<br />
> OCIHandle -> Ptr OCIHandle -> CInt -> CInt -> Ptr a -> IO CInt<br />
><br />
> handleAlloc :: CInt -> OCIHandle -> IO OCIHandle<br />
> handleAlloc handleType env = alloca $ \ptr -> do<br />
> rc <- ociHandleAlloc env ptr handleType 0 nullPtr<br />
> if rc < 0<br />
> then throwOCI (OCIException rc "allocate handle")<br />
> else peek ptr<br />
</haskell><br />
<br />
''(Shouldn't that be "... else peek ptr"?)''<br />
<br />
''(yes, it should. Fixed)''<br />
<br />
Here, memory is allocated for ptr, and then it is passed to the foreign function.<br />
<hask>alloca</hask> is prefered because it frees the memory for ptr when the function exits,<br />
or when an exception is raised.<br />
We use <hask>peek</hask> to get at the value returned.<br />
<hask>alloca</hask> takes an IO action which takes a single argument: the newly allocated ptr.<br />
We use a lambda expression here to create an anonymous function (actually an IO action).<br />
<br />
<br />
==== Multiple argument case ====<br />
<br />
If the function modifies more than one of its arguments, then things get a little more complex.<br />
In this case we have to allocate the memory for the arguments<br />
(again, using the <hask>alloca*</hask> family of functions),<br />
call the C function, and extract the values.<br />
In this example the <hask>ociErrorGet</hask> function modifies the third and fourth args<br />
(int and string respectively).<br />
I've chosen an arbitrary size for the buffer for the string: 1000 bytes.<br />
<br />
<haskell><br />
> getOCIErrorMsg2 :: OCIHandle -> CInt -> Ptr CInt -> CString -> CInt -> IO (CInt, String)<br />
> getOCIErrorMsg2 ocihandle handleType errCodePtr errMsgBuf maxErrMsgLen = do<br />
> rc <- ociErrorGet ocihandle 1 0 errCodePtr errMsgBuf maxErrMsgLen handleType<br />
> if rc < 0<br />
> then return (0, "Error message not available.")<br />
> else do<br />
> msg <- peekCString errMsg<br />
> e <- peek errCode<br />
> return (e, msg)<br />
><br />
> getOCIErrorMsg :: OCIHandle -> CInt -> IO (CInt, String)<br />
> getOCIErrorMsg ocihandle handleType = do<br />
> let stringBufferLen = 1000<br />
> allocaBytes stringBufferLen $ \errMsg -><br />
> alloca $ \errCode -><br />
> getOCIErrorMsg2 ocihandle handleType errCode errMsg (mkCInt stringBufferLen)<br />
</haskell><br />
<br />
(Thanks to Udo Stenzel for tips for avoiding memory leaks.)<br />
<br />
=== Passing strings ===<br />
<br />
'''Problem:'''<br />
C function expects strings with lengths, where each string <hask>(char*)</hask><br />
is followed by an int stating how long it is.<br />
<br />
'''Solution:'''<br />
Convert Haskell Strings to <hask>CStringLens</hask>, and<br />
pull <hask>CStringLens</hask> apart with utility functions.<br />
A <hask>CStringLen</hask> is just a <hask>(CString, Int)</hask> pair.<br />
Would it have been better to make <hask>CStringLen</hask> a <hask>(CString, CInt)</hask> pair?<br />
<br />
<haskell><br />
> mkCInt :: Int -> CInt<br />
> mkCInt n = fromIntegral n<br />
> cStrLen :: CStringLen -> CInt<br />
> cStrLen = mkCInt . snd<br />
> cStr :: CStringLen -> CString<br />
> cStr = fst<br />
><br />
> dbLogon :: String -> String -> String -> EnvHandle -> ErrorHandle -> IO ConnHandle<br />
> dbLogon user pswd db env err =<br />
> withCStringLen user $ \userC -><br />
> withCStringLen pswd $ \pswdC -><br />
> withCStringLen db $ \dbC -><br />
> alloca $ \conn -> do<br />
> rc <- ociLogon env err conn (cStr userC) (cStrLen userC) (cStr pswdC) (cStrLen pswdC) (cStr dbC) (cStrLen dbC)<br />
> case () of<br />
> _ | rc == oci_SUCCESS_WITH_INFO -> testForErrorWithPtr oci_ERROR "logon" conn<br />
> | otherwise -> testForErrorWithPtr rc "logon" conn<br />
</haskell><br />
<br />
=== Working with structs ===<br />
<br />
''Please check me''<br />
<br />
For example suppose you had a struct like:<br />
<br />
<haskell><br />
typedef struct {<br />
int a;<br />
char b;<br />
double c;<br />
} my_struct;<br />
</haskell><br />
<br />
And you wanted to write a storable instance. Here pre-processing with hsc2hs tool can be helpfull. You would write it like this:<br />
<br />
<haskell><br />
instance Storable Struct where<br />
alignment _ = #{alignment my_struct}<br />
sizeOf _ = #{size my_struct}<br />
peek ptr = do<br />
a <- #{peek my_struct, a} ptr<br />
b <- #{peek my_struct, b} ptr<br />
c <- #{peek my_struct, c} ptr<br />
return (MyStruct a, b, c)<br />
poke ptr (MyStruct a b c) = do<br />
#{poke my_struct, a} ptr a<br />
#{poke my_struct, b} ptr b<br />
#{poke my_struct, c} ptr c<br />
</haskell><br />
<br />
Note that the #{alignment foo} syntax is not currently built-in to hsc2hs. You<br />
have to add the following line to your haskell source file to add the alignment syntax:<br />
<br />
<haskell><br />
#let alignment t = "%lu", (unsigned long)offsetof(struct {char x__; t<br />
(y__); }, y__)<br />
</haskell><br />
<br />
With a string field (struct { char c_string_field[MAX_LEN]; }) you would have to do it a little different. For example in peek:<br />
<br />
<haskell><br />
peek ptr = do<br />
s <- peekCString $ #{ptr c_type,c_string_field} ptr<br />
return (Foo s)<br />
</haskell><br />
<br />
Then in poke you would do:<br />
<br />
<haskell><br />
poke ptr (Foo s) = do<br />
withCStringLen (take maxLen value) $ uncurry (copyArray $ #{ptr<br />
c_type,c_string_field} ptr)<br />
where maxLen = #{const MAX_LEN}<br />
</haskell><br />
<br />
Note the use of #{ptr} instead of #{peek} since we want the address of<br />
the c_string_field rather than it's value. Unfortunately for the<br />
"struct { char *c_string_field; }" style there is no good general<br />
solution because you have to worry about allocating memory to have<br />
c_string_field point to.<br />
<br />
<br />
<br />
== Calling C functions in DLL ==<br />
by Ronald Guida, hCafe, 12 sep 2007<br />
<br />
1. I can leave "test_foo.lhs" and "foo.cpp" as-is:<br />
<br />
foo.cpp:<br />
<haskell><br />
#include "foo.h"<br />
<br />
__stdcall int foo(int x)<br />
{<br />
return 3 * x + 1;<br />
}<br />
</haskell><br />
<br />
test_foo.lhs:<br />
<haskell><br />
> {-# OPTIONS_GHC -fglasgow-exts #-}<br />
> module Main<br />
> where<br />
> import Foreign<br />
> import Foreign.C<br />
<br />
> foreign import stdcall unsafe "foo"<br />
> c_Foo :: Word32 -> IO Word32<br />
<br />
> main = do<br />
> putStrLn "Entering main"<br />
> let x = 7::Word32<br />
> y <- c_Foo(x)<br />
> putStrLn $ "y = " ++ show y<br />
> putStrLn "Exiting main"<br />
</haskell><br />
<br />
2. I need to change "foo.h" to the following:<br />
<haskell><br />
#if BUILD_DLL<br />
#define DECLSPEC __declspec(dllexport)<br />
#else<br />
#define DECLSPEC __declspec(dllimport)<br />
#endif<br />
<br />
extern "C"<br />
{<br />
DECLSPEC __stdcall int foo(int x);<br />
}<br />
</haskell><br />
<br />
3. I need to create a "foo.def" file and list the functions to be exported in a DLL:<br />
<haskell><br />
LIBRARY foo<br />
DESCRIPTION "Foo Library"<br />
EXPORTS<br />
foo<br />
</haskell><br />
<br />
Note: The library name on the first line must match the dll name. "LIBRARY foo" corresponds to "foo.dll"<br />
<br />
4. The build process is as follows.<br />
<br />
(1) gcc -DBUILD_DLL -c foo.cpp<br />
<br />
(2) gcc -shared -o foo.dll foo.o foo.def \<br />
-Wl,--enable-stdcall-fixup,--out-implib,libfoo.a<br />
<br />
5. At this point, I'll have "foo.dll" and "libfoo.a". I can load my<br />
"foo" library, as a DLL, into GHCi with the command:<br />
$ ghci -lfoo<br />
In reality, I would use:<br />
$ ghci test_foo.lhs -lfoo<br />
<br />
6. Once I'm satisfied and ready to compile:<br />
<br />
ghc --make test_foo.lhs -L. -lfoo<br />
<br />
Notes:<br />
(1) "-L." directs GHC to look in the current directory for<br />
libraries. GHCi seems to look there by default.<br />
<br />
(2) The resulting "test_foo.exe" will dynamicly load "foo.dll".<br />
<br />
7. If I want a staticly linked executable instead:<br />
<br />
ar rcs libfoo_static.a foo.o<br />
ghc --make test_foo.lhs -L. -lfoo_static<br />
<br />
8. Finally, I can put the build steps into a Makefile:<br />
<br />
<haskell><br />
# Makefile for foo<br />
<br />
test_foo.exe : test_foo.lhs libfoo.a foo.dll<br />
ghc --make test_foo.lhs -L. -lfoo<br />
<br />
test_foo_static.exe : test_foo.lhs libfoo_static.a<br />
ghc --make test_foo.lhs -L. -lfoo_static -o test_foo_static.exe<br />
<br />
libfoo.a : foo.dll<br />
<br />
foo.dll : foo.o foo.def<br />
gcc -shared -o foo.dll foo.o foo.def \<br />
-Wl,--enable-stdcall-fixup,--out-implib,libfoo.a<br />
<br />
libfoo_static.a : foo.o<br />
ar rcs libfoo_static.a foo.o<br />
<br />
foo.o : foo.cpp foo.h<br />
gcc -DBUILD_DLL -c foo.cpp<br />
<br />
.PHONY: clean<br />
clean:<br />
rm -f *.[oa]<br />
rm -f *.dll<br />
rm -f *.hi<br />
rm -f *.exe<br />
</haskell><br />
<br />
<br />
<br />
== Calling C++ functions in a Visual Studio DLL from Haskell, and Haskell functions from the C++ DLL ==<br />
<br />
[[GHC/Using_the_FFI|This material is placed on the separate page]]<br />
<br />
<br />
<br />
== Raising and handling exceptions ==<br />
<br />
Follow the advice for Dynamic Exceptions, in:<br />
http://www.haskell.org/ghc/docs/latest/html/libraries/base/Control.Exception.html#10<br />
<br />
Create your own exceptions, and your own throw and catch functions.<br />
This makes it easier to trap only exceptions raised by your code.<br />
<br />
<haskell><br />
> data OCIException = OCIException Int String deriving (Typeable, Show)<br />
><br />
> catchOCI :: IO a -> (OCIException -> IO a) -> IO a<br />
> catchOCI = catchDyn<br />
> throwOCI :: OCIException -> a<br />
> throwOCI = throwDyn<br />
<br />
If we can't derive Typeable then the following code should do the trick:<br />
<br />
> -- replaces:<br />
> data OCIException = OCIException CInt String deriving (Show)<br />
> ociExceptionTc :: TyCon<br />
> ociExceptionTc = mkTyCon "Database.Oracle.OciFunctions.OCIException"<br />
> instance Typeable OCIException where typeOf _ = mkAppTy ociExceptionTc []<br />
</haskell><br />
<br />
<br />
Use the catch functions like this:<br />
(Here convertAndRethrow converts the low-level FFI exceptions<br />
from one module into higher (application-level) exceptions.)<br />
<br />
<haskell><br />
> commit :: Session -> IO ()<br />
> commit (Session env err conn) = catchOCI ( do<br />
> OCI.commitTrans err conn<br />
> ) (\exc -> convertAndRethrow err exc nullAction)<br />
><br />
> nullAction :: IO ()<br />
> nullAction = return ()<br />
><br />
> convertAndRethrow :: ErrorHandle -> OCIException -> IO () -> IO ()<br />
> convertAndRethrow err exc cleanupAction = do<br />
> (e, m) <- OCI.formatErrorMsg exc err<br />
> cleanupAction<br />
> throwDB (DBError e m)<br />
</haskell><br />
<br />
Or, an example that must do some cleanup when the exception is thrown:<br />
(Note also that the exception handler must return a value of the<br />
same type as the main action.)<br />
<br />
<haskell><br />
> logon :: String -> String -> String -> EnvHandle -> ErrorHandle -> IO ConnHandle<br />
> logon user pswd dbname env err = catchOCI ( do<br />
> connection <- OCI.dbLogon user pswd dbname env err<br />
> return connection<br />
> ) (\ociexc -> do<br />
> convertAndRethrow err ociexc $ do<br />
> freeHandle (castPtr err) oci_HTYPE_ERROR<br />
> freeHandle (castPtr env) oci_HTYPE_ENV<br />
> return undefined<br />
> )<br />
</haskell><br />
<br />
----<br />
''Suppose I've got a pointer-to-function, a !FunPtr. How do I call the pointed-to function from Haskell?<br />
(This is a real problem: When I tried to create a binding to Libdb 4, all functions are actually !FunPtrs contained in structs. I really don't want to write a C function that extracts and dereferences the pointer for every single one of them.)'' -- UdoStenzel<br />
<br />
I haven't done this before, so I can only suggest looking at the docs and experimenting:<br />
http://www.haskell.org/ghc/docs/latest/html/libraries/base/Foreign.Ptr.html#t%3AFunPtr<br />
<br />
This comment (from that Foreign.Ptr page) might help: "To convert !FunPtr values to corresponding Haskell functions, one can define a dynamic stub for the specific foreign type, e.g.<br />
<br />
<haskell><br />
type IntFunction = CInt -> IO ()<br />
foreign import ccall "dynamic" <br />
mkFun :: FunPtr IntFunction -> IntFunction<br />
</haskell><br />
<br />
''Thanks, I somehow missed that note. Now it seems for every !FunPtr in some structure I need to define a seperate dynamic import? This is annoying, I'd have to spell out the type of every such function at least twice (three times when counting the convenient Haskell wrapper)! Is there a way around it? Maybe a preprocessor (c2hs comes close, but doesn't seem to handle !FunPtrs)?'' -- UdoStenzel<br />
<br />
That is what [[HSFFIG]] tries to address, especially related to function pointers held in structures' fields, and parsing of their type signatures. And problems with BerkeleyDB described above sort of inspired creation of HSFFIG. See also the HsffigExamples page. <br />
<br />
What HSFFIG does not do well yet, is autocreation of dynamic wrappers for !FunPtrs passed as other functions' parameters and/or return values: this is available only in part and not always done in consistent way. -- DimitryGolubovsky<br />
<br />
[[Category:Tutorials]]</div>Briqueabraquehttps://wiki.haskell.org/index.php?title=Keywords&diff=22665Keywords2008-08-28T12:00:27Z<p>Briqueabraque: </p>
<hr />
<div>This page lists all Haskell keywords, feel free to edit. [[Hoogle]] searches will return results from this page. Please respect the Anchor macros.<br />
<br />
For additional information you might want to look at [http://www.haskell.org/onlinereport/ the Haskell 98 report].<br />
<br />
== | ==<br />
<br />
The "pipe" is used in several places<br />
<br />
Data type definitions, "or"<br />
<br />
<haskell><br />
data Maybe a = Just a | Nothing<br />
</haskell><br />
<br />
List comprehensions, "where"<br />
<br />
<haskell><br />
squares = [a*a | a <- [1..]]<br />
</haskell><br />
<br />
Guards, do this "if this is true"<br />
<br />
<haskell><br />
safeTail x | null x = []<br />
| otherwise = tail x<br />
</haskell><br />
<br />
== -> ==<br />
<br />
The function type constructor:<br />
<haskell><br />
length :: [a] -> Int<br />
</haskell><br />
<br />
In lambdas:<br />
<haskell><br />
\x -> x + 1<br />
</haskell><br />
<br />
To denote alternatives in case statements:<br />
<haskell><br />
case Just 3 of<br />
Nothing -> False<br />
Just x -> True<br />
</haskell><br />
<br />
And on the kind level (GHC specific):<br />
<haskell><br />
(->) :: ?? -> ? -> *<br />
</haskell><br />
<br />
== <- ==<br />
<br />
In do-notation:<br />
<haskell><br />
do x <- getChar<br />
putChar x<br />
</haskell><br />
<br />
In list comprehension generators:<br />
<haskell><br />
[ (x,y) | x <- [1..10], y <- ['a'..'z'] ]<br />
</haskell><br />
<br />
In pattern guards (a GHC extension):<br />
<haskell><br />
f x y | Just z <- g x = True<br />
| otherwise = False<br />
</haskell><br />
<br />
== @ ==<br />
<br />
Patterns of the form var@pat are called as-patterns, and allow one to<br />
use var as a name for the value being matched by pat. For example:<br />
<haskell><br />
case e of { xs@(x:rest) -> if x==0 then rest else xs }<br />
</haskell><br />
<br />
is equivalent to:<br />
<br />
<haskell><br />
let { xs = e } in<br />
case xs of { (x:rest) -> if x==0 then rest else xs }<br />
</haskell><br />
<br />
== ! ==<br />
<br />
Whenever a data [[constructor]] is applied, each argument to the<br />
constructor is evaluated if and only if the corresponding type in the<br />
algebraic data[[type]] declaration has a strictness flag, denoted by an<br />
exclamation point. For example:<br />
<br />
<haskell><br />
data STList a <br />
= STCons a !(STList a) -- the second argument to STCons will be <br />
-- evaluated before STCons is applied<br />
| STNil<br />
</haskell><br />
<br />
to illustrate the difference between strict versus lazy constructor<br />
application, consider the following:<br />
<br />
<haskell><br />
stList = STCons 1 undefined<br />
lzList = (:) 1 undefined<br />
stHead (STCons h _) = h -- this evaluates to undefined when applied to stList<br />
lzHead (h : _) = h -- this evaluates to 1 when applied to lzList<br />
</haskell><br />
<br />
! is also used in the "bang patterns" (GHC extension), to indicate<br />
strictness in patterns:<br />
<br />
<haskell><br />
f !x !y = x + y<br />
</haskell><br />
<br />
Finally, it is the array subscript operator:<br />
<haskell><br />
let x = arr ! 10<br />
</haskell><br />
<br />
== :: ==<br />
<br />
Read as "has type":<br />
<br />
<haskell><br />
length :: [a] -> Int<br />
</haskell><br />
<br />
"Length has type list-of-'a' to Int"<br />
<br />
== _ ==<br />
<br />
Patterns of the form _ are wildcards and are useful when some part of a<br />
pattern is not referenced on the right-hand-side. It is as if an<br />
identifier not used elsewhere were put in its place. For example,<br />
<br />
<haskell><br />
case e of { [x,_,_] -> if x==0 then True else False }<br />
</haskell><br />
<br />
is equivalent to:<br />
<br />
<haskell><br />
case e of { [x,y,z] -> if x==0 then True else False }<br />
</haskell><br />
<br />
== ~ ==<br />
<br />
Lazy pattern bindings. Matching the pattern ~pat against a value always<br />
suceeds, and matching will only diverge when one of the variables bound<br />
in the pattern is used.<br />
<br />
<haskell><br />
f1,f2 :: Maybe Int -> String;<br />
(+++),(++++) :: (a->b)->(c->d)->(a,c)->(b,d);<br />
<br />
f1 x = case x of {Just n -> "Got it"};<br />
f2 x = case x of {~(Just n) -> "Got it"};<br />
<br />
(f +++ g) ~(x,y) = (f x , g y);<br />
(f ++++ g) (x,y) = (f x , g y);<br />
</haskell><br />
<br />
Then we have:<br />
<br />
<haskell><br />
f1 Nothing<br />
Exception: Non-exhaustive patterns in case<br />
<br />
f2 Nothing<br />
"Got it"<br />
<br />
(const 1 +++ const 2) undefined<br />
(1,2)<br />
<br />
(const 1 ++++ const 2) undefined<br />
Exception: Prelude.undefined<br />
</haskell><br />
<br />
== -- ==<br />
<br />
Line comment character. Everything after <hask>--</hask> on a line is ignored.<br />
<br />
<haskell><br />
main = print "hello world" -- comment here<br />
</haskell><br />
<br />
The multiline variant of comments is <hask>{- comment -}</hask>.<br />
<br />
== > ==<br />
<br />
In a bird style [[Literate_programming|Literate Haskell file]], the > character is used to introduce a code line.<br />
<br />
<haskell><br />
comment line<br />
> main = print "hello world"<br />
</haskell><br />
<br />
== as ==<br />
<br />
Renaming module imports. Like <hask>qualified</hask> and <hask>hiding</hask>, <hask>as</hask> is not a reserved word but may be used as function or variable name.<br />
<br />
<haskell><br />
import qualified Data.Map as M<br />
<br />
main = print (M.empty :: M.Map Int ())<br />
</haskell><br />
<br />
== <span id="case">case</span>, <span id="of">of</span> ==<br />
<br />
A case expression has the general form<br />
<br />
<haskell><br />
case e of { p1 match1 ; ... ; pn matchn }<br />
</haskell><br />
<br />
where each match is of the general form<br />
<br />
<haskell><br />
| g1 -> e1<br />
...<br />
| gm -> em<br />
where decls<br />
</haskell><br />
<br />
Each alternative consists of a pattern pi and its matches, matchi. Each<br />
match in turn consists of a sequence of pairs of guards gj and bodies ej<br />
(expressions), followed by optional bindings (decls) that scope over all<br />
of the guards and expressions of the alternative. An alternative of the<br />
form<br />
<br />
<haskell><br />
pat -> exp where decls<br />
</haskell><br />
<br />
is treated as shorthand for:<br />
<br />
<haskell><br />
pat | True -> exp<br />
where decls<br />
</haskell><br />
<br />
A case expression must have at least one alternative and each<br />
alternative must have at least one body. Each body must have the same<br />
type, and the type of the whole expression is that type.<br />
<br />
A case expression is evaluated by pattern matching the expression e<br />
against the individual alternatives. The alternatives are tried<br />
sequentially, from top to bottom. If e matches the pattern in the<br />
alternative, the guards for that alternative are tried sequentially from<br />
top to bottom, in the environment of the case expression extended first<br />
by the bindings created during the matching of the pattern, and then by<br />
the declsi in the where clause associated with that alternative. If one<br />
of the guards evaluates to True, the corresponding right-hand side is<br />
evaluated in the same environment as the guard. If all the guards<br />
evaluate to False, matching continues with the next alternative. If no<br />
match succeeds, the result is _|_.<br />
<br />
== class ==<br />
<br />
A [http://haskell.org/onlinereport/decls.html#class-decls class declaration] <br />
introduces a new type class and the overloaded operations that must be<br />
supported by any type that is an instance of that class.<br />
<haskell><br />
class Num a where<br />
(+) :: a -> a -> a<br />
negate :: a -> a<br />
</haskell><br />
<br />
== data ==<br />
<br />
The [http://haskell.org/onlinereport/decls.html#user-defined-datatypes data] <br />
declaration is how one introduces new algebraic data [[type]]s into<br />
Haskell. For example:<br />
<br />
<haskell><br />
data Set a = NilSet <br />
| ConsSet a (Set a)<br />
</haskell><br />
<br />
Another example, to create a datatype to hold an [[Abstract syntax<br />
tree]] for an expression, one could use:<br />
<br />
<haskell><br />
data Exp = Ebin Operator Exp Exp <br />
| Eunary Operator Exp <br />
| Efun FunctionIdentifier [Exp] <br />
| Eid SimpleIdentifier<br />
</haskell><br />
<br />
where the [[type]]s <code>Operator, FunctionIdentifier</code> and <code>SimpleIdentifier</code> are defined elsewhere. <br />
<br />
See the page on [[type]]s for more information, links and examples.<br />
<br />
== default ==<br />
<br />
Ambiguities in the class Num are most common, so Haskell provides<br />
a way to resolve them---with a default declaration:<br />
<br />
<haskell><br />
default (Int)<br />
</haskell><br />
<br />
Only one default declaration is permitted per module, and its effect is<br />
limited to that module. If no default declaration is given in a module<br />
then it assumed to be:<br />
<br />
<haskell><br />
default (Integer, Double)<br />
</haskell><br />
<br />
== deriving ==<br />
<br />
data and newtype declarations contain an optional deriving form. If the<br />
form is included, then derived instance declarations are automatically<br />
generated for the datatype in each of the named classes.<br />
<br />
[http://haskell.org/onlinereport/decls.html#derived-decls Derived instances] provide convenient commonly-used operations for user-defined<br />
datatypes. For example, derived instances for datatypes in the class Eq<br />
define the operations == and /=, freeing the programmer from the need to<br />
define them.<br />
<br />
<haskell><br />
data T = A<br />
| B<br />
| C<br />
deriving (Eq, Ord, Show)<br />
</haskell><br />
<br />
== do ==<br />
<br />
Syntactic sugar for use with monadic expressions. For example:<br />
<br />
<haskell><br />
do { x ; result <- y ; foo result }<br />
</haskell><br />
<br />
is shorthand for:<br />
<br />
<haskell><br />
x >> <br />
y >>= \result -><br />
foo result<br />
</haskell><br />
<br />
== forall ==<br />
<br />
This is a GHC/Hugs extension, and as such is not portable Haskell 98. <br />
It is only a reserved word within types. <br />
<br />
Type variables in a Haskell type expression are all assumed to be<br />
universally quantified; there is no explicit syntax for universal<br />
quantification, in standard Haskell 98. For example, the type expression<br />
<hask>a -> a</hask> denotes the type <hask>forall a. a ->a</hask>. <br />
For clarity, however, we often write quantification explicitly when<br />
discussing the types of Haskell programs. When we write an explicitly<br />
quantified type, the scope of the forall extends as far to the right as<br />
possible; for example, <br />
<haskell><br />
forall a. a -> a<br />
</haskell><br />
means <br />
<haskell><br />
forall a. (a -> a)<br />
</haskell><br />
<br />
GHC [http://www.haskell.org/ghc/docs/latest/html/users_guide/type-extensions.html#type-synonyms introduces] a <hask>forall</hask> keyword, allowing explicit quantification, for example, to encode <br />
[http://www.haskell.org/ghc/docs/latest/html/users_guide/type-extensions.html#existential-quantification existential types]: <br />
<haskell><br />
data Foo = forall a. MkFoo a (a -> Bool)<br />
| Nil<br />
<br />
MkFoo :: forall a. a -> (a -> Bool) -> Foo<br />
Nil :: Foo<br />
<br />
[MkFoo 3 even, MkFoo 'c' isUpper] :: [Foo]<br />
</haskell><br />
<br />
== foreign ==<br />
<br />
A keyword for the foreign function interface that is enabled by -ffi, -fffi<br />
or implied by -fglasgow-exts<br />
<br />
== hiding ==<br />
<br />
When importing modules, without introducing a name into scope, entities can be excluded by using the form<br />
<haskell><br />
hiding (import1 , ... , importn )<br />
</haskell><br />
which specifies that all entities exported by the named module should be<br />
imported except for those named in the list.<br />
<br />
For example:<br />
<haskell><br />
import Prelude hiding (lookup,filter,foldr,foldl,null,map)<br />
</haskell><br />
<br />
== <span id="if">if</span>, <span id="then">then</span>, <span id="else">else</span> ==<br />
<br />
A conditional expression has the form:<br />
<br />
<haskell><br />
if e1 then e2 else e3<br />
</haskell><br />
<br />
and returns the value of e2 if the value of e1 is True, e3 if e1 is False, and _|_ otherwise.<br />
<br />
<haskell><br />
max a b = if a > b then a else b<br />
</haskell><br />
<br />
== import ==<br />
<br />
[http://haskell.org/onlinereport/modules.html Modules] may reference<br />
other modules via explicit import declarations, each giving the name of<br />
a module to be imported and specifying its entities to be imported.<br />
<br />
For example:<br />
<haskell><br />
module Main where<br />
import A<br />
import B<br />
main = A.f >> B.f<br />
<br />
module A where<br />
f = ...<br />
<br />
module B where<br />
f = ...<br />
</haskell><br />
<br />
See also <hask>as</hask>, <hask>hiding</hask> and <hask>qualified</hask><br />
<br />
== <span id="infix">infix</span>, <span id="infixl">infixl</span>, <span id="infixr">infixr</span> ==<br />
<br />
A [http://haskell.org/onlinereport/decls.html fixity declaration] gives<br />
the fixity and binding precedence of one or more operators. The integer<br />
in a fixity declaration must be in the range 0 to 9. A fixity<br />
declaration may appear anywhere that a type signature appears and, like<br />
a type signature, declares a property of a particular operator.<br />
<br />
There are three kinds of fixity, non-, left- and right-associativity<br />
(infix, infixl, and infixr, respectively), and ten precedence levels, 0<br />
to 9 inclusive (level 0 binds least tightly, and level 9 binds most<br />
tightly).<br />
<br />
<haskell><br />
module Bar where<br />
infixr 7 `op`<br />
op = ...<br />
</haskell><br />
<br />
== instance ==<br />
<br />
An instance declaration declares that a type is an instance of a class<br />
and includes the definitions of the overloaded operations - called class<br />
methods - instantiated on the named type.<br />
<br />
<haskell><br />
instance Num Int where<br />
x + y = addInt x y<br />
negate x = negateInt x<br />
</haskell><br />
<br />
== <span id="let">let</span>, <span id="in">in</span> ==<br />
<br />
Let expressions have the general form:<br />
<br />
<haskell>let { d1 ; ... ; dn } in e</haskell><br />
<br />
They introduce a nested, lexically-scoped, mutually-recursive list of declarations (let is often called letrec in other languages). The scope of the declarations is the expression e and the right hand side of the declarations.<br />
<br />
Within <hask>do</hask>-blocks or list comprehensions <hask>let { d1 ; ... ; dn }</hask> without <hask>in</hask> serves to indroduce local bindings.<br />
<br />
== mdo ==<br />
<br />
the recursive <hask>do</hask> keyword enabled by -fglasgow-exts<br />
<br />
== module ==<br />
<br />
taken from: http://www.haskell.org/tutorial/modules.html<br />
<br />
Technically speaking, a module is really just one big declaration which begins with the keyword module; here's an example for a module whose name is Tree:<br />
<br />
<haskell><br />
module Tree ( Tree(Leaf,Branch), fringe ) where<br />
<br />
data Tree a = Leaf a | Branch (Tree a) (Tree a) <br />
<br />
fringe :: Tree a -> [a]<br />
fringe (Leaf x) = [x]<br />
fringe (Branch left right) = fringe left ++ fringe right<br />
</haskell><br />
<br />
== newtype ==<br />
<br />
The <code>newtype</code> declaration is how one introduces a renaming for an algebraic data [[type]] into Haskell. This is different from <code>type</code> below, as a <code>newtype</code> requires a new [[constructor]] as well. As an example, when writing a compiler<br />
one sometimes further qualifies <code>Identifier</code>s to assist in type safety checks:<br />
<br />
newtype SimpleIdentifier = SimpleIdentifier Identifier<br />
newtype FunctionIdentifier = FunctionIdentifier Identifier<br />
<br />
Most often, one supplies [[smart constructors]] and [[destructor]]s for these to ease working with them.<br />
<br />
See the page on [[type]]s for more information, links and examples.<br />
<br />
For the differences between <code>newtype</code> and <code>data</code>, see [[Newtype]].<br />
<br />
== qualified ==<br />
<br />
Used to import a module, but not introduce a name into scope. For example, Data.Map exports lookup, which would clash with the Prelude version of lookup, to fix this:<br />
<br />
<haskell><br />
import qualified Data.Map<br />
<br />
f x = lookup x -- use the Prelude version<br />
g x = Data.Map.lookup x -- use the Data.Map version<br />
</haskell><br />
<br />
Of course, Data.Map is a bit of a mouthful, so qualified also allows the use of as.<br />
<br />
<haskell><br />
import qualified Data.Map as M<br />
<br />
f x = lookup x -- use Prelude version<br />
g x = M.lookup x -- use Data.Map version<br />
</haskell><br />
<br />
== type ==<br />
<br />
The <code>type</code> declaration is how one introduces an alias for an algebraic data [[type]] into Haskell. As an example, when writing a compiler<br />
one often creates an alias for identifiers:<br />
<br />
<haskell><br />
type Identifier = String<br />
</haskell><br />
<br />
This allows you to use <code>Identifer</code> wherever you had used <code>String</code> and if something is of type <code>Identifier</code> it<br />
may be used wherever a <code>String</code> is expected.<br />
<br />
See the page on [[type]]s for more information, links and examples.<br />
<br />
Some common <code>type</code> declarations in the Prelude include:<br />
<br />
<haskell><br />
type FilePath = String<br />
type String = [Char]<br />
type Rational = Ratio Integer<br />
type ReadS a = String -> [(a,String)]<br />
type ShowS = String -> String<br />
</haskell><br />
<br />
== where ==<br />
<br />
Used to introduce a module, instance or class:<br />
<haskell><br />
module Main where<br />
<br />
class Num a where<br />
...<br />
<br />
instance Num Int where<br />
...<br />
</haskell><br />
<br />
And to bind local variables:<br />
<haskell><br />
f x = y<br />
where y = x * 2<br />
<br />
g z | z > 2 = y<br />
where y = x * 2<br />
</haskell><br />
<br />
<br />
[[Category:Language]]</div>Briqueabraquehttps://wiki.haskell.org/index.php?title=Keywords&diff=22664Keywords2008-08-28T11:58:58Z<p>Briqueabraque: </p>
<hr />
<div>This page lists all Haskell keywords, feel free to edit. [[Hoogle]] searches will return results from this page. Please respect the Anchor macros.<br />
<br />
For additional information you might want to look at [http://www.haskell.org/onlinereport/ the Haskell 98 report].<br />
<br />
== | ==<br />
<br />
The "pipe" is used in several places<br />
<br />
Data type definitions, "or"<br />
<br />
<haskell><br />
data Maybe a = Just a | Nothing<br />
</haskell><br />
<br />
List comprehensions, "where"<br />
<br />
<haskell><br />
squares = [a*a | a <- [1..]]<br />
</haskell><br />
<br />
Guards, do this "if this is true"<br />
<br />
<haskell><br />
safeTail x | null x = []<br />
| otherwise = tail x<br />
</haskell><br />
<br />
== -> ==<br />
<br />
The function type constructor:<br />
<haskell><br />
length :: [a] -> Int<br />
</haskell><br />
<br />
In lambdas:<br />
<haskell><br />
\x -> x + 1<br />
</haskell><br />
<br />
To denote alternatives in case statements:<br />
<haskell><br />
case Just 3 of<br />
Nothing -> False<br />
Just x -> True<br />
</haskell><br />
<br />
And on the kind level (GHC specific):<br />
<haskell><br />
(->) :: ?? -> ? -> *<br />
</haskell><br />
<br />
== <- ==<br />
<br />
In do-notation:<br />
<haskell><br />
do x <- getChar<br />
putChar x<br />
</haskell><br />
<br />
In list comprehension generators:<br />
<haskell><br />
[ (x,y) | x <- [1..10], y <- ['a'..'z'] ]<br />
</haskell><br />
<br />
In pattern guards (a GHC extension):<br />
<haskell><br />
f x y | Just z <- g x = True<br />
| otherwise = False<br />
</haskell><br />
<br />
== @ ==<br />
<br />
Patterns of the form var@pat are called as-patterns, and allow one to<br />
use var as a name for the value being matched by pat. For example:<br />
<haskell><br />
case e of { xs@(x:rest) -> if x==0 then rest else xs }<br />
</haskell><br />
<br />
is equivalent to:<br />
<br />
<haskell><br />
let { xs = e } in<br />
case xs of { (x:rest) -> if x==0 then rest else xs }<br />
</haskell><br />
<br />
== ! ==<br />
<br />
Whenever a data [[constructor]] is applied, each argument to the<br />
constructor is evaluated if and only if the corresponding type in the<br />
algebraic data[[type]] declaration has a strictness flag, denoted by an<br />
exclamation point. For example:<br />
<br />
<haskell><br />
data STList a <br />
= STCons a !(STList a) -- the second argument to STCons will be <br />
-- evaluated before STCons is applied<br />
| STNil<br />
</haskell><br />
<br />
to illustrate the difference between strict versus lazy constructor<br />
application, consider the following:<br />
<br />
<haskell><br />
stList = STCons 1 undefined<br />
lzList = (:) 1 undefined<br />
stHead (STCons h _) = h -- this evaluates to undefined when applied to stList<br />
lzHead (h : _) = h -- this evaluates to 1 when applied to lzList<br />
</haskell><br />
<br />
! is also used in the "bang patterns" (GHC extension), to indicate<br />
strictness in patterns:<br />
<br />
<haskell><br />
f !x !y = x + y<br />
</haskell><br />
<br />
Finally, it is the array subscript operator:<br />
<haskell><br />
let x = arr ! 10<br />
</haskell><br />
<br />
== :: ==<br />
<br />
Read as "has type":<br />
<br />
<haskell><br />
length :: [a] -> Int<br />
</haskell><br />
<br />
"Length has type list-of-'a' to Int"<br />
<br />
== _ ==<br />
<br />
Patterns of the form _ are wildcards and are useful when some part of a<br />
pattern is not referenced on the right-hand-side. It is as if an<br />
identifier not used elsewhere were put in its place. For example,<br />
<br />
<haskell><br />
case e of { [x,_,_] -> if x==0 then True else False }<br />
</haskell><br />
<br />
is equivalent to:<br />
<br />
<haskell><br />
case e of { [x,y,z] -> if x==0 then True else False }<br />
</haskell><br />
<br />
== ~ ==<br />
<br />
Lazy pattern bindings. Matching the pattern ~pat against a value always<br />
suceeds, and matching will only diverge when one of the variables bound<br />
in the pattern is used.<br />
<br />
<haskell><br />
f1,f2 :: Maybe Int -> String;<br />
(+++),(++++) :: (a->b)->(c->d)->(a,c)->(b,d);<br />
<br />
f1 x = case x of {Just n -> "Got it"};<br />
f2 x = case x of {~(Just n) -> "Got it"};<br />
<br />
(f +++ g) ~(x,y) = (f x , g y);<br />
(f ++++ g) (x,y) = (f x , g y);<br />
</haskell><br />
<br />
Then we have:<br />
<br />
f1 Nothing<br />
Exception: exemplo.hs:4:7-36: Non-exhaustive patterns in case<br />
<br />
f2 Nothing<br />
"Got it"<br />
<br />
(const 1 +++ const 2) undefined<br />
(1,2)<br />
<br />
(const 1 ++++ const 2) undefined<br />
Exception: Prelude.undefined<br />
<br />
== -- ==<br />
<br />
Line comment character. Everything after <hask>--</hask> on a line is ignored.<br />
<br />
<haskell><br />
main = print "hello world" -- comment here<br />
</haskell><br />
<br />
The multiline variant of comments is <hask>{- comment -}</hask>.<br />
<br />
== > ==<br />
<br />
In a bird style [[Literate_programming|Literate Haskell file]], the > character is used to introduce a code line.<br />
<br />
<haskell><br />
comment line<br />
> main = print "hello world"<br />
</haskell><br />
<br />
== as ==<br />
<br />
Renaming module imports. Like <hask>qualified</hask> and <hask>hiding</hask>, <hask>as</hask> is not a reserved word but may be used as function or variable name.<br />
<br />
<haskell><br />
import qualified Data.Map as M<br />
<br />
main = print (M.empty :: M.Map Int ())<br />
</haskell><br />
<br />
== <span id="case">case</span>, <span id="of">of</span> ==<br />
<br />
A case expression has the general form<br />
<br />
<haskell><br />
case e of { p1 match1 ; ... ; pn matchn }<br />
</haskell><br />
<br />
where each match is of the general form<br />
<br />
<haskell><br />
| g1 -> e1<br />
...<br />
| gm -> em<br />
where decls<br />
</haskell><br />
<br />
Each alternative consists of a pattern pi and its matches, matchi. Each<br />
match in turn consists of a sequence of pairs of guards gj and bodies ej<br />
(expressions), followed by optional bindings (decls) that scope over all<br />
of the guards and expressions of the alternative. An alternative of the<br />
form<br />
<br />
<haskell><br />
pat -> exp where decls<br />
</haskell><br />
<br />
is treated as shorthand for:<br />
<br />
<haskell><br />
pat | True -> exp<br />
where decls<br />
</haskell><br />
<br />
A case expression must have at least one alternative and each<br />
alternative must have at least one body. Each body must have the same<br />
type, and the type of the whole expression is that type.<br />
<br />
A case expression is evaluated by pattern matching the expression e<br />
against the individual alternatives. The alternatives are tried<br />
sequentially, from top to bottom. If e matches the pattern in the<br />
alternative, the guards for that alternative are tried sequentially from<br />
top to bottom, in the environment of the case expression extended first<br />
by the bindings created during the matching of the pattern, and then by<br />
the declsi in the where clause associated with that alternative. If one<br />
of the guards evaluates to True, the corresponding right-hand side is<br />
evaluated in the same environment as the guard. If all the guards<br />
evaluate to False, matching continues with the next alternative. If no<br />
match succeeds, the result is _|_.<br />
<br />
== class ==<br />
<br />
A [http://haskell.org/onlinereport/decls.html#class-decls class declaration] <br />
introduces a new type class and the overloaded operations that must be<br />
supported by any type that is an instance of that class.<br />
<haskell><br />
class Num a where<br />
(+) :: a -> a -> a<br />
negate :: a -> a<br />
</haskell><br />
<br />
== data ==<br />
<br />
The [http://haskell.org/onlinereport/decls.html#user-defined-datatypes data] <br />
declaration is how one introduces new algebraic data [[type]]s into<br />
Haskell. For example:<br />
<br />
<haskell><br />
data Set a = NilSet <br />
| ConsSet a (Set a)<br />
</haskell><br />
<br />
Another example, to create a datatype to hold an [[Abstract syntax<br />
tree]] for an expression, one could use:<br />
<br />
<haskell><br />
data Exp = Ebin Operator Exp Exp <br />
| Eunary Operator Exp <br />
| Efun FunctionIdentifier [Exp] <br />
| Eid SimpleIdentifier<br />
</haskell><br />
<br />
where the [[type]]s <code>Operator, FunctionIdentifier</code> and <code>SimpleIdentifier</code> are defined elsewhere. <br />
<br />
See the page on [[type]]s for more information, links and examples.<br />
<br />
== default ==<br />
<br />
Ambiguities in the class Num are most common, so Haskell provides<br />
a way to resolve them---with a default declaration:<br />
<br />
<haskell><br />
default (Int)<br />
</haskell><br />
<br />
Only one default declaration is permitted per module, and its effect is<br />
limited to that module. If no default declaration is given in a module<br />
then it assumed to be:<br />
<br />
<haskell><br />
default (Integer, Double)<br />
</haskell><br />
<br />
== deriving ==<br />
<br />
data and newtype declarations contain an optional deriving form. If the<br />
form is included, then derived instance declarations are automatically<br />
generated for the datatype in each of the named classes.<br />
<br />
[http://haskell.org/onlinereport/decls.html#derived-decls Derived instances] provide convenient commonly-used operations for user-defined<br />
datatypes. For example, derived instances for datatypes in the class Eq<br />
define the operations == and /=, freeing the programmer from the need to<br />
define them.<br />
<br />
<haskell><br />
data T = A<br />
| B<br />
| C<br />
deriving (Eq, Ord, Show)<br />
</haskell><br />
<br />
== do ==<br />
<br />
Syntactic sugar for use with monadic expressions. For example:<br />
<br />
<haskell><br />
do { x ; result <- y ; foo result }<br />
</haskell><br />
<br />
is shorthand for:<br />
<br />
<haskell><br />
x >> <br />
y >>= \result -><br />
foo result<br />
</haskell><br />
<br />
== forall ==<br />
<br />
This is a GHC/Hugs extension, and as such is not portable Haskell 98. <br />
It is only a reserved word within types. <br />
<br />
Type variables in a Haskell type expression are all assumed to be<br />
universally quantified; there is no explicit syntax for universal<br />
quantification, in standard Haskell 98. For example, the type expression<br />
<hask>a -> a</hask> denotes the type <hask>forall a. a ->a</hask>. <br />
For clarity, however, we often write quantification explicitly when<br />
discussing the types of Haskell programs. When we write an explicitly<br />
quantified type, the scope of the forall extends as far to the right as<br />
possible; for example, <br />
<haskell><br />
forall a. a -> a<br />
</haskell><br />
means <br />
<haskell><br />
forall a. (a -> a)<br />
</haskell><br />
<br />
GHC [http://www.haskell.org/ghc/docs/latest/html/users_guide/type-extensions.html#type-synonyms introduces] a <hask>forall</hask> keyword, allowing explicit quantification, for example, to encode <br />
[http://www.haskell.org/ghc/docs/latest/html/users_guide/type-extensions.html#existential-quantification existential types]: <br />
<haskell><br />
data Foo = forall a. MkFoo a (a -> Bool)<br />
| Nil<br />
<br />
MkFoo :: forall a. a -> (a -> Bool) -> Foo<br />
Nil :: Foo<br />
<br />
[MkFoo 3 even, MkFoo 'c' isUpper] :: [Foo]<br />
</haskell><br />
<br />
== foreign ==<br />
<br />
A keyword for the foreign function interface that is enabled by -ffi, -fffi<br />
or implied by -fglasgow-exts<br />
<br />
== hiding ==<br />
<br />
When importing modules, without introducing a name into scope, entities can be excluded by using the form<br />
<haskell><br />
hiding (import1 , ... , importn )<br />
</haskell><br />
which specifies that all entities exported by the named module should be<br />
imported except for those named in the list.<br />
<br />
For example:<br />
<haskell><br />
import Prelude hiding (lookup,filter,foldr,foldl,null,map)<br />
</haskell><br />
<br />
== <span id="if">if</span>, <span id="then">then</span>, <span id="else">else</span> ==<br />
<br />
A conditional expression has the form:<br />
<br />
<haskell><br />
if e1 then e2 else e3<br />
</haskell><br />
<br />
and returns the value of e2 if the value of e1 is True, e3 if e1 is False, and _|_ otherwise.<br />
<br />
<haskell><br />
max a b = if a > b then a else b<br />
</haskell><br />
<br />
== import ==<br />
<br />
[http://haskell.org/onlinereport/modules.html Modules] may reference<br />
other modules via explicit import declarations, each giving the name of<br />
a module to be imported and specifying its entities to be imported.<br />
<br />
For example:<br />
<haskell><br />
module Main where<br />
import A<br />
import B<br />
main = A.f >> B.f<br />
<br />
module A where<br />
f = ...<br />
<br />
module B where<br />
f = ...<br />
</haskell><br />
<br />
See also <hask>as</hask>, <hask>hiding</hask> and <hask>qualified</hask><br />
<br />
== <span id="infix">infix</span>, <span id="infixl">infixl</span>, <span id="infixr">infixr</span> ==<br />
<br />
A [http://haskell.org/onlinereport/decls.html fixity declaration] gives<br />
the fixity and binding precedence of one or more operators. The integer<br />
in a fixity declaration must be in the range 0 to 9. A fixity<br />
declaration may appear anywhere that a type signature appears and, like<br />
a type signature, declares a property of a particular operator.<br />
<br />
There are three kinds of fixity, non-, left- and right-associativity<br />
(infix, infixl, and infixr, respectively), and ten precedence levels, 0<br />
to 9 inclusive (level 0 binds least tightly, and level 9 binds most<br />
tightly).<br />
<br />
<haskell><br />
module Bar where<br />
infixr 7 `op`<br />
op = ...<br />
</haskell><br />
<br />
== instance ==<br />
<br />
An instance declaration declares that a type is an instance of a class<br />
and includes the definitions of the overloaded operations - called class<br />
methods - instantiated on the named type.<br />
<br />
<haskell><br />
instance Num Int where<br />
x + y = addInt x y<br />
negate x = negateInt x<br />
</haskell><br />
<br />
== <span id="let">let</span>, <span id="in">in</span> ==<br />
<br />
Let expressions have the general form:<br />
<br />
<haskell>let { d1 ; ... ; dn } in e</haskell><br />
<br />
They introduce a nested, lexically-scoped, mutually-recursive list of declarations (let is often called letrec in other languages). The scope of the declarations is the expression e and the right hand side of the declarations.<br />
<br />
Within <hask>do</hask>-blocks or list comprehensions <hask>let { d1 ; ... ; dn }</hask> without <hask>in</hask> serves to indroduce local bindings.<br />
<br />
== mdo ==<br />
<br />
the recursive <hask>do</hask> keyword enabled by -fglasgow-exts<br />
<br />
== module ==<br />
<br />
taken from: http://www.haskell.org/tutorial/modules.html<br />
<br />
Technically speaking, a module is really just one big declaration which begins with the keyword module; here's an example for a module whose name is Tree:<br />
<br />
<haskell><br />
module Tree ( Tree(Leaf,Branch), fringe ) where<br />
<br />
data Tree a = Leaf a | Branch (Tree a) (Tree a) <br />
<br />
fringe :: Tree a -> [a]<br />
fringe (Leaf x) = [x]<br />
fringe (Branch left right) = fringe left ++ fringe right<br />
</haskell><br />
<br />
== newtype ==<br />
<br />
The <code>newtype</code> declaration is how one introduces a renaming for an algebraic data [[type]] into Haskell. This is different from <code>type</code> below, as a <code>newtype</code> requires a new [[constructor]] as well. As an example, when writing a compiler<br />
one sometimes further qualifies <code>Identifier</code>s to assist in type safety checks:<br />
<br />
newtype SimpleIdentifier = SimpleIdentifier Identifier<br />
newtype FunctionIdentifier = FunctionIdentifier Identifier<br />
<br />
Most often, one supplies [[smart constructors]] and [[destructor]]s for these to ease working with them.<br />
<br />
See the page on [[type]]s for more information, links and examples.<br />
<br />
For the differences between <code>newtype</code> and <code>data</code>, see [[Newtype]].<br />
<br />
== qualified ==<br />
<br />
Used to import a module, but not introduce a name into scope. For example, Data.Map exports lookup, which would clash with the Prelude version of lookup, to fix this:<br />
<br />
<haskell><br />
import qualified Data.Map<br />
<br />
f x = lookup x -- use the Prelude version<br />
g x = Data.Map.lookup x -- use the Data.Map version<br />
</haskell><br />
<br />
Of course, Data.Map is a bit of a mouthful, so qualified also allows the use of as.<br />
<br />
<haskell><br />
import qualified Data.Map as M<br />
<br />
f x = lookup x -- use Prelude version<br />
g x = M.lookup x -- use Data.Map version<br />
</haskell><br />
<br />
== type ==<br />
<br />
The <code>type</code> declaration is how one introduces an alias for an algebraic data [[type]] into Haskell. As an example, when writing a compiler<br />
one often creates an alias for identifiers:<br />
<br />
<haskell><br />
type Identifier = String<br />
</haskell><br />
<br />
This allows you to use <code>Identifer</code> wherever you had used <code>String</code> and if something is of type <code>Identifier</code> it<br />
may be used wherever a <code>String</code> is expected.<br />
<br />
See the page on [[type]]s for more information, links and examples.<br />
<br />
Some common <code>type</code> declarations in the Prelude include:<br />
<br />
<haskell><br />
type FilePath = String<br />
type String = [Char]<br />
type Rational = Ratio Integer<br />
type ReadS a = String -> [(a,String)]<br />
type ShowS = String -> String<br />
</haskell><br />
<br />
== where ==<br />
<br />
Used to introduce a module, instance or class:<br />
<haskell><br />
module Main where<br />
<br />
class Num a where<br />
...<br />
<br />
instance Num Int where<br />
...<br />
</haskell><br />
<br />
And to bind local variables:<br />
<haskell><br />
f x = y<br />
where y = x * 2<br />
<br />
g z | z > 2 = y<br />
where y = x * 2<br />
</haskell><br />
<br />
<br />
[[Category:Language]]</div>Briqueabraquehttps://wiki.haskell.org/index.php?title=Keywords&diff=22661Keywords2008-08-28T11:51:41Z<p>Briqueabraque: </p>
<hr />
<div>This page lists all Haskell keywords, feel free to edit. [[Hoogle]] searches will return results from this page. Please respect the Anchor macros.<br />
<br />
For additional information you might want to look at [http://www.haskell.org/onlinereport/ the Haskell 98 report].<br />
<br />
== | ==<br />
<br />
The "pipe" is used in several places<br />
<br />
Data type definitions, "or"<br />
<br />
<haskell><br />
data Maybe a = Just a | Nothing<br />
</haskell><br />
<br />
List comprehensions, "where"<br />
<br />
<haskell><br />
squares = [a*a | a <- [1..]]<br />
</haskell><br />
<br />
Guards, do this "if this is true"<br />
<br />
<haskell><br />
safeTail x | null x = []<br />
| otherwise = tail x<br />
</haskell><br />
<br />
== -> ==<br />
<br />
The function type constructor:<br />
<haskell><br />
length :: [a] -> Int<br />
</haskell><br />
<br />
In lambdas:<br />
<haskell><br />
\x -> x + 1<br />
</haskell><br />
<br />
To denote alternatives in case statements:<br />
<haskell><br />
case Just 3 of<br />
Nothing -> False<br />
Just x -> True<br />
</haskell><br />
<br />
And on the kind level (GHC specific):<br />
<haskell><br />
(->) :: ?? -> ? -> *<br />
</haskell><br />
<br />
== <- ==<br />
<br />
In do-notation:<br />
<haskell><br />
do x <- getChar<br />
putChar x<br />
</haskell><br />
<br />
In list comprehension generators:<br />
<haskell><br />
[ (x,y) | x <- [1..10], y <- ['a'..'z'] ]<br />
</haskell><br />
<br />
In pattern guards (a GHC extension):<br />
<haskell><br />
f x y | Just z <- g x = True<br />
| otherwise = False<br />
</haskell><br />
<br />
== @ ==<br />
<br />
Patterns of the form var@pat are called as-patterns, and allow one to<br />
use var as a name for the value being matched by pat. For example:<br />
<haskell><br />
case e of { xs@(x:rest) -> if x==0 then rest else xs }<br />
</haskell><br />
<br />
is equivalent to:<br />
<br />
<haskell><br />
let { xs = e } in<br />
case xs of { (x:rest) -> if x==0 then rest else xs }<br />
</haskell><br />
<br />
== ! ==<br />
<br />
Whenever a data [[constructor]] is applied, each argument to the<br />
constructor is evaluated if and only if the corresponding type in the<br />
algebraic data[[type]] declaration has a strictness flag, denoted by an<br />
exclamation point. For example:<br />
<br />
<haskell><br />
data STList a <br />
= STCons a !(STList a) -- the second argument to STCons will be <br />
-- evaluated before STCons is applied<br />
| STNil<br />
</haskell><br />
<br />
to illustrate the difference between strict versus lazy constructor<br />
application, consider the following:<br />
<br />
<haskell><br />
stList = STCons 1 undefined<br />
lzList = (:) 1 undefined<br />
stHead (STCons h _) = h -- this evaluates to undefined when applied to stList<br />
lzHead (h : _) = h -- this evaluates to 1 when applied to lzList<br />
</haskell><br />
<br />
! is also used in the "bang patterns" (GHC extension), to indicate<br />
strictness in patterns:<br />
<br />
<haskell><br />
f !x !y = x + y<br />
</haskell><br />
<br />
Finally, it is the array subscript operator:<br />
<haskell><br />
let x = arr ! 10<br />
</haskell><br />
<br />
== :: ==<br />
<br />
Read as "has type":<br />
<br />
<haskell><br />
length :: [a] -> Int<br />
</haskell><br />
<br />
"Length has type list-of-'a' to Int"<br />
<br />
== _ ==<br />
<br />
Patterns of the form _ are wildcards and are useful when some part of a<br />
pattern is not referenced on the right-hand-side. It is as if an<br />
identifier not used elsewhere were put in its place. For example,<br />
<br />
<haskell><br />
case e of { [x,_,_] -> if x==0 then True else False }<br />
</haskell><br />
<br />
is equivalent to:<br />
<br />
<haskell><br />
case e of { [x,y,z] -> if x==0 then True else False }<br />
</haskell><br />
<br />
== ~ ==<br />
<br />
Lazy pattern bindings. Matching the pattern ~pat against a value always<br />
suceeds, and matching will only diverge when one of the variables bound<br />
in the pattern is used.<br />
<br />
<haskell><br />
f1,f2 :: Maybe Int -> String;<br />
(***),(****) :: (a->b)->(c->d)->(a,c)->(b,d);<br />
<br />
f1 x = case x of {Just n -> "Got it"};<br />
f2 x = case x of {~(Just n) -> "Got it"};<br />
<br />
(f *** g) ~(x,y) = (f x , g y);<br />
(f **** g) (x,y) = (f x , g y);<br />
</haskell><br />
<br />
Then we have:<br />
<br />
f1 Nothing<br />
*** Exception: exemplo.hs:4:7-36: Non-exhaustive patterns in case<br />
<br />
f2 Nothing<br />
"Got it"<br />
<br />
(const 1 *** const 2) undefined<br />
(1,2)<br />
<br />
(const 1 **** const 2) undefined<br />
*** Exception: Prelude.undefined<br />
<br />
== -- ==<br />
<br />
Line comment character. Everything after <hask>--</hask> on a line is ignored.<br />
<br />
<haskell><br />
main = print "hello world" -- comment here<br />
</haskell><br />
<br />
The multiline variant of comments is <hask>{- comment -}</hask>.<br />
<br />
== > ==<br />
<br />
In a bird style [[Literate_programming|Literate Haskell file]], the > character is used to introduce a code line.<br />
<br />
<haskell><br />
comment line<br />
> main = print "hello world"<br />
</haskell><br />
<br />
== as ==<br />
<br />
Renaming module imports. Like <hask>qualified</hask> and <hask>hiding</hask>, <hask>as</hask> is not a reserved word but may be used as function or variable name.<br />
<br />
<haskell><br />
import qualified Data.Map as M<br />
<br />
main = print (M.empty :: M.Map Int ())<br />
</haskell><br />
<br />
== <span id="case">case</span>, <span id="of">of</span> ==<br />
<br />
A case expression has the general form<br />
<br />
<haskell><br />
case e of { p1 match1 ; ... ; pn matchn }<br />
</haskell><br />
<br />
where each match is of the general form<br />
<br />
<haskell><br />
| g1 -> e1<br />
...<br />
| gm -> em<br />
where decls<br />
</haskell><br />
<br />
Each alternative consists of a pattern pi and its matches, matchi. Each<br />
match in turn consists of a sequence of pairs of guards gj and bodies ej<br />
(expressions), followed by optional bindings (decls) that scope over all<br />
of the guards and expressions of the alternative. An alternative of the<br />
form<br />
<br />
<haskell><br />
pat -> exp where decls<br />
</haskell><br />
<br />
is treated as shorthand for:<br />
<br />
<haskell><br />
pat | True -> exp<br />
where decls<br />
</haskell><br />
<br />
A case expression must have at least one alternative and each<br />
alternative must have at least one body. Each body must have the same<br />
type, and the type of the whole expression is that type.<br />
<br />
A case expression is evaluated by pattern matching the expression e<br />
against the individual alternatives. The alternatives are tried<br />
sequentially, from top to bottom. If e matches the pattern in the<br />
alternative, the guards for that alternative are tried sequentially from<br />
top to bottom, in the environment of the case expression extended first<br />
by the bindings created during the matching of the pattern, and then by<br />
the declsi in the where clause associated with that alternative. If one<br />
of the guards evaluates to True, the corresponding right-hand side is<br />
evaluated in the same environment as the guard. If all the guards<br />
evaluate to False, matching continues with the next alternative. If no<br />
match succeeds, the result is _|_.<br />
<br />
== class ==<br />
<br />
A [http://haskell.org/onlinereport/decls.html#class-decls class declaration] <br />
introduces a new type class and the overloaded operations that must be<br />
supported by any type that is an instance of that class.<br />
<haskell><br />
class Num a where<br />
(+) :: a -> a -> a<br />
negate :: a -> a<br />
</haskell><br />
<br />
== data ==<br />
<br />
The [http://haskell.org/onlinereport/decls.html#user-defined-datatypes data] <br />
declaration is how one introduces new algebraic data [[type]]s into<br />
Haskell. For example:<br />
<br />
<haskell><br />
data Set a = NilSet <br />
| ConsSet a (Set a)<br />
</haskell><br />
<br />
Another example, to create a datatype to hold an [[Abstract syntax<br />
tree]] for an expression, one could use:<br />
<br />
<haskell><br />
data Exp = Ebin Operator Exp Exp <br />
| Eunary Operator Exp <br />
| Efun FunctionIdentifier [Exp] <br />
| Eid SimpleIdentifier<br />
</haskell><br />
<br />
where the [[type]]s <code>Operator, FunctionIdentifier</code> and <code>SimpleIdentifier</code> are defined elsewhere. <br />
<br />
See the page on [[type]]s for more information, links and examples.<br />
<br />
== default ==<br />
<br />
Ambiguities in the class Num are most common, so Haskell provides<br />
a way to resolve them---with a default declaration:<br />
<br />
<haskell><br />
default (Int)<br />
</haskell><br />
<br />
Only one default declaration is permitted per module, and its effect is<br />
limited to that module. If no default declaration is given in a module<br />
then it assumed to be:<br />
<br />
<haskell><br />
default (Integer, Double)<br />
</haskell><br />
<br />
== deriving ==<br />
<br />
data and newtype declarations contain an optional deriving form. If the<br />
form is included, then derived instance declarations are automatically<br />
generated for the datatype in each of the named classes.<br />
<br />
[http://haskell.org/onlinereport/decls.html#derived-decls Derived instances] provide convenient commonly-used operations for user-defined<br />
datatypes. For example, derived instances for datatypes in the class Eq<br />
define the operations == and /=, freeing the programmer from the need to<br />
define them.<br />
<br />
<haskell><br />
data T = A<br />
| B<br />
| C<br />
deriving (Eq, Ord, Show)<br />
</haskell><br />
<br />
== do ==<br />
<br />
Syntactic sugar for use with monadic expressions. For example:<br />
<br />
<haskell><br />
do { x ; result <- y ; foo result }<br />
</haskell><br />
<br />
is shorthand for:<br />
<br />
<haskell><br />
x >> <br />
y >>= \result -><br />
foo result<br />
</haskell><br />
<br />
== forall ==<br />
<br />
This is a GHC/Hugs extension, and as such is not portable Haskell 98. <br />
It is only a reserved word within types. <br />
<br />
Type variables in a Haskell type expression are all assumed to be<br />
universally quantified; there is no explicit syntax for universal<br />
quantification, in standard Haskell 98. For example, the type expression<br />
<hask>a -> a</hask> denotes the type <hask>forall a. a ->a</hask>. <br />
For clarity, however, we often write quantification explicitly when<br />
discussing the types of Haskell programs. When we write an explicitly<br />
quantified type, the scope of the forall extends as far to the right as<br />
possible; for example, <br />
<haskell><br />
forall a. a -> a<br />
</haskell><br />
means <br />
<haskell><br />
forall a. (a -> a)<br />
</haskell><br />
<br />
GHC [http://www.haskell.org/ghc/docs/latest/html/users_guide/type-extensions.html#type-synonyms introduces] a <hask>forall</hask> keyword, allowing explicit quantification, for example, to encode <br />
[http://www.haskell.org/ghc/docs/latest/html/users_guide/type-extensions.html#existential-quantification existential types]: <br />
<haskell><br />
data Foo = forall a. MkFoo a (a -> Bool)<br />
| Nil<br />
<br />
MkFoo :: forall a. a -> (a -> Bool) -> Foo<br />
Nil :: Foo<br />
<br />
[MkFoo 3 even, MkFoo 'c' isUpper] :: [Foo]<br />
</haskell><br />
<br />
== foreign ==<br />
<br />
A keyword for the foreign function interface that is enabled by -ffi, -fffi<br />
or implied by -fglasgow-exts<br />
<br />
== hiding ==<br />
<br />
When importing modules, without introducing a name into scope, entities can be excluded by using the form<br />
<haskell><br />
hiding (import1 , ... , importn )<br />
</haskell><br />
which specifies that all entities exported by the named module should be<br />
imported except for those named in the list.<br />
<br />
For example:<br />
<haskell><br />
import Prelude hiding (lookup,filter,foldr,foldl,null,map)<br />
</haskell><br />
<br />
== <span id="if">if</span>, <span id="then">then</span>, <span id="else">else</span> ==<br />
<br />
A conditional expression has the form:<br />
<br />
<haskell><br />
if e1 then e2 else e3<br />
</haskell><br />
<br />
and returns the value of e2 if the value of e1 is True, e3 if e1 is False, and _|_ otherwise.<br />
<br />
<haskell><br />
max a b = if a > b then a else b<br />
</haskell><br />
<br />
== import ==<br />
<br />
[http://haskell.org/onlinereport/modules.html Modules] may reference<br />
other modules via explicit import declarations, each giving the name of<br />
a module to be imported and specifying its entities to be imported.<br />
<br />
For example:<br />
<haskell><br />
module Main where<br />
import A<br />
import B<br />
main = A.f >> B.f<br />
<br />
module A where<br />
f = ...<br />
<br />
module B where<br />
f = ...<br />
</haskell><br />
<br />
See also <hask>as</hask>, <hask>hiding</hask> and <hask>qualified</hask><br />
<br />
== <span id="infix">infix</span>, <span id="infixl">infixl</span>, <span id="infixr">infixr</span> ==<br />
<br />
A [http://haskell.org/onlinereport/decls.html fixity declaration] gives<br />
the fixity and binding precedence of one or more operators. The integer<br />
in a fixity declaration must be in the range 0 to 9. A fixity<br />
declaration may appear anywhere that a type signature appears and, like<br />
a type signature, declares a property of a particular operator.<br />
<br />
There are three kinds of fixity, non-, left- and right-associativity<br />
(infix, infixl, and infixr, respectively), and ten precedence levels, 0<br />
to 9 inclusive (level 0 binds least tightly, and level 9 binds most<br />
tightly).<br />
<br />
<haskell><br />
module Bar where<br />
infixr 7 `op`<br />
op = ...<br />
</haskell><br />
<br />
== instance ==<br />
<br />
An instance declaration declares that a type is an instance of a class<br />
and includes the definitions of the overloaded operations - called class<br />
methods - instantiated on the named type.<br />
<br />
<haskell><br />
instance Num Int where<br />
x + y = addInt x y<br />
negate x = negateInt x<br />
</haskell><br />
<br />
== <span id="let">let</span>, <span id="in">in</span> ==<br />
<br />
Let expressions have the general form:<br />
<br />
<haskell>let { d1 ; ... ; dn } in e</haskell><br />
<br />
They introduce a nested, lexically-scoped, mutually-recursive list of declarations (let is often called letrec in other languages). The scope of the declarations is the expression e and the right hand side of the declarations.<br />
<br />
Within <hask>do</hask>-blocks or list comprehensions <hask>let { d1 ; ... ; dn }</hask> without <hask>in</hask> serves to indroduce local bindings.<br />
<br />
== mdo ==<br />
<br />
the recursive <hask>do</hask> keyword enabled by -fglasgow-exts<br />
<br />
== module ==<br />
<br />
taken from: http://www.haskell.org/tutorial/modules.html<br />
<br />
Technically speaking, a module is really just one big declaration which begins with the keyword module; here's an example for a module whose name is Tree:<br />
<br />
<haskell><br />
module Tree ( Tree(Leaf,Branch), fringe ) where<br />
<br />
data Tree a = Leaf a | Branch (Tree a) (Tree a) <br />
<br />
fringe :: Tree a -> [a]<br />
fringe (Leaf x) = [x]<br />
fringe (Branch left right) = fringe left ++ fringe right<br />
</haskell><br />
<br />
== newtype ==<br />
<br />
The <code>newtype</code> declaration is how one introduces a renaming for an algebraic data [[type]] into Haskell. This is different from <code>type</code> below, as a <code>newtype</code> requires a new [[constructor]] as well. As an example, when writing a compiler<br />
one sometimes further qualifies <code>Identifier</code>s to assist in type safety checks:<br />
<br />
newtype SimpleIdentifier = SimpleIdentifier Identifier<br />
newtype FunctionIdentifier = FunctionIdentifier Identifier<br />
<br />
Most often, one supplies [[smart constructors]] and [[destructor]]s for these to ease working with them.<br />
<br />
See the page on [[type]]s for more information, links and examples.<br />
<br />
For the differences between <code>newtype</code> and <code>data</code>, see [[Newtype]].<br />
<br />
== qualified ==<br />
<br />
Used to import a module, but not introduce a name into scope. For example, Data.Map exports lookup, which would clash with the Prelude version of lookup, to fix this:<br />
<br />
<haskell><br />
import qualified Data.Map<br />
<br />
f x = lookup x -- use the Prelude version<br />
g x = Data.Map.lookup x -- use the Data.Map version<br />
</haskell><br />
<br />
Of course, Data.Map is a bit of a mouthful, so qualified also allows the use of as.<br />
<br />
<haskell><br />
import qualified Data.Map as M<br />
<br />
f x = lookup x -- use Prelude version<br />
g x = M.lookup x -- use Data.Map version<br />
</haskell><br />
<br />
== type ==<br />
<br />
The <code>type</code> declaration is how one introduces an alias for an algebraic data [[type]] into Haskell. As an example, when writing a compiler<br />
one often creates an alias for identifiers:<br />
<br />
<haskell><br />
type Identifier = String<br />
</haskell><br />
<br />
This allows you to use <code>Identifer</code> wherever you had used <code>String</code> and if something is of type <code>Identifier</code> it<br />
may be used wherever a <code>String</code> is expected.<br />
<br />
See the page on [[type]]s for more information, links and examples.<br />
<br />
Some common <code>type</code> declarations in the Prelude include:<br />
<br />
<haskell><br />
type FilePath = String<br />
type String = [Char]<br />
type Rational = Ratio Integer<br />
type ReadS a = String -> [(a,String)]<br />
type ShowS = String -> String<br />
</haskell><br />
<br />
== where ==<br />
<br />
Used to introduce a module, instance or class:<br />
<haskell><br />
module Main where<br />
<br />
class Num a where<br />
...<br />
<br />
instance Num Int where<br />
...<br />
</haskell><br />
<br />
And to bind local variables:<br />
<haskell><br />
f x = y<br />
where y = x * 2<br />
<br />
g z | z > 2 = y<br />
where y = x * 2<br />
</haskell><br />
<br />
<br />
[[Category:Language]]</div>Briqueabraque