https://wiki.haskell.org/api.php?action=feedcontributions&user=Ulfn&feedformat=atomHaskellWiki - User contributions [en]2015-05-04T18:20:50ZUser contributionsMediaWiki 1.19.14+dfsg-1https://wiki.haskell.org/OpenGLOpenGL2010-07-22T10:04:26Z<p>Ulfn: changed darcs links to point to code.haskell.org</p>
<hr />
<div>{{Stub}}<br />
This is a stub page for Haskell's OpenGL and GLUT bindings. It is meant as a starting point to replace the outdated and misleading documentation at the<br />
[http://www.haskell.org/HOpenGL-old/ old page].<br />
<br />
First, note that the implementation is far more up-to-date than that old page suggested (originally, it was quite useful, but the page hasn't kept up with the implementation for a long time now).<br />
<br />
== References == <br />
* [http://www.haskell.org/mailman/listinfo/hopengl the HOpenGL mailing list]<br />
<br />
* [http://hackage.haskell.org/packages/archive/OpenGL/latest/doc/html/ the API docs for the OpenGL binding]<br />
<br />
* [http://hackage.haskell.org/packages/archive/GLUT/latest/doc/html/ the API docs for the GLUT binding]<br />
<br />
* [http://code.haskell.org/OpenGL/ the darcs repo with the sources for the OpenGL binding]<br />
<br />
* [http://code.haskell.org/GLUT/ the darcs repo with the sources for the GLUT binding]<br />
<br />
In particular, note that the [http://code.haskell.org/GLUT/examples/ examples/] directory in the GLUT repo contains lots of examples, including translations of the red book examples.<br />
<br />
(Note: at least some of these resources appear to be missing from [http://darcs.haskell.org/packages/ /packages], but there are copies at [http://darcs.haskell.org/ghc-6.8/packages/ /ghc-6.8/packages].)<br />
<br />
Both the API documentation and the examples are best studied with the [http://www.opengl.org/documentation/specs/ original specs] and the original [http://www.opengl.org/documentation/red_book/ red book] examples at hand. An index of the examples from v1.1 of the red book, with screen shots, can be found [http://www.opengl.org/resources/code/samples/redbook/ here].<br />
<br />
== Projects using the OpenGL bindings == <br />
<br />
* [http://www.increpare.com/2008/11/endless-cavern/ Endless Cavern], a 2D procedurally-generated exploration game.<br />
* [[Frag]], a 3D first-person shooter game.<br />
* [http://www.geocities.jp/takascience/haskell/monadius_en.html Monadius], a 2D scrolling arcade game.<br />
* [http://roguestar.downstairspeople.org/ Roguestar], a roguelike adventure game using 3D graphics.<br />
* [http://hackage.haskell.org/cgi-bin/hackage-scripts/package/Shu-thing Shu-thing], a 2D scroling arcade game.<br />
* [http://home.arcor.de/chr_bauer/topkata.html Topkata], a jumping ball puzzle game.<br />
* [http://www.comp.leeds.ac.uk/funvis/ PolyFunViz], a toolkit for scientific visualization (e.g. surfaces, flows, contours, volumes)<br />
* [http://raincat.bysusanlin.com Raincat], a 2d puzzle game<br />
<br />
== HOpenGL Resources == <br />
<br />
* [[OpenGLTutorial1]] and [[OpenGLTutorial2]]<br />
* [http://www.renci.org/publications/tutorials/BeautifulCode.pdf Beautiful Code, Compelling Evidence: Functional Programming for Information Visualization and Visual Analytics] - Writing visualizations using OpenGL or Cairo (PDF)<br />
* [http://www.cin.ufpe.br/~haskell/hopengl/ Andre Furtado's nice tutorial] written in 2001 (bitrotted)<br />
* [http://www.haskell.org/~pairwise/HOpenGL/HOpenGL.html#texLoad Spriting with HOpenGL], David Morra<br />
<br />
== OpenGL Resources ==<br />
<br />
* [http://www.opengl.org/resources/faq/technical/ OpenGL FAQ and Toubleshooting Guide] Assumes some knowledge of OpenGL. Good for those who have written something but want to avoid common pitfalls.<br />
** [http://www.opengl.org/resources/faq/technical/gettingstarted.htm#0050 2.100: What is the general form of an OpenGL program?]<br />
<br />
== Getting Started ==<br />
<br />
* Windows users can read how to install OpenGL in the blog article [http://netsuperbrain.com/blog/posts/freeglut-windows-hopengl-hglut/ freeglut + Windows + HOpenGL + HGLUT]<br />
* assuming you know Haskell, any OpenGL tutorial of your choice should get you going (browsing the [http://www.opengl.org OpenGL] site is also a good idea)<br />
* use the [http://www.opengl.org/documentation/red_book/ Red Book], and its example code translations, to understand the small differences between OpenGL and HOpenGL<br />
* use the [http://www.opengl.org/documentation/specs/ OpenGL and GLUT specs] to find your way around the [http://hackage.haskell.org/packages/archive/OpenGL/latest/doc/html/ HOpenGL Haddock documentation]<br />
* use the [http://www.haskell.org/mailman/listinfo/hopengl HopenGL list] for questions and success stories<br />
<br />
== Additional software == <br />
* [http://hackage.haskell.org/package/OpenGLRaw OpenGLRaw]: A 1:1 mapping of OpenGL's C API, intended as a basis for a nicer interface<br />
* [http://hackage.haskell.org/package/StateVar StateVar]: This package contains state variables, which are references in the IO monad, like IORefs or parts of the OpenGL state<br />
* [http://hackage.haskell.org/package/ObjectName ObjectName]: Explicitly handled object names. This tiny package contains the class ObjectName, which corresponds to the general notion of explicitly handled identifiers for API objects, e.g. a texture object name in OpenGL or a buffer object name in OpenAL<br />
* [http://hackage.haskell.org/package/GLURaw GLURaw]: A raw binding for the OpenGL graphics system. GLURaw is a raw Haskell binding for the GLU 1.3 OpenGL utility library. It is basically a 1:1 mapping of GLU's C API, intended as a basis for a nicer interface<br />
* [[FTGL]]: Portable TrueType font rendering for OpenGL using the Freetype2 library<br />
* [http://hackage.haskell.org/cgi-bin/hackage-scripts/package/GLFW GLFW]: A binding for GLFW, An OpenGL Framework<br />
* [http://hackage.haskell.org/cgi-bin/hackage-scripts/package/GLUT GLUT]: A binding for the OpenGL Utility Toolkit<br />
* [http://hackage.haskell.org/cgi-bin/hackage-scripts/package/graphics-drawingcombinators graphics-drawingcombinators]: A functional interface to 2D drawing in OpenGL<br />
* [http://hackage.haskell.org/package/Tensor Tensor]: This package contains tensor data types and their instances for some basic type classes.<br />
* [http://hackage.haskell.org/package/GPipe GPipe]: A functional graphics API for programmable GPUs<br />
<br />
Somewhat related is [http://www.libsdl.org/ SDL], which is also based on OpenGL:<br />
* [http://hackage.haskell.org/cgi-bin/hackage-scripts/package/SDL SDL]: Binding to libSDL<br />
* [http://hackage.haskell.org/cgi-bin/hackage-scripts/package/SDL-gfx SDL-gfx]: Binding to libSDL_gfx<br />
* [http://hackage.haskell.org/cgi-bin/hackage-scripts/package/SDL-image SDL-image]: Binding to libSDL_image<br />
* [http://hackage.haskell.org/cgi-bin/hackage-scripts/package/SDL-mixer SDL-mixer]: Binding to libSDL_mixer<br />
* [http://hackage.haskell.org/cgi-bin/hackage-scripts/package/SDL-mpeg SDL-mpeg]: Binding to the SMPEG library <br />
* [http://hackage.haskell.org/cgi-bin/hackage-scripts/package/SDL-ttf SDL-ttf]: Binding to libSDL_ttf<br />
<br />
To add sound to OpenGL applications:<br />
* [http://hackage.haskell.org/cgi-bin/hackage-scripts/package/OpenAL OpenAL]: A binding to the [[OpenAL]] cross-platform 3D audio API<br />
* [http://hackage.haskell.org/cgi-bin/hackage-scripts/package/ALUT ALUT]: A binding for the OpenAL Utility Toolkit<br />
<br />
A fork of HOpenGL:<br />
* [[OGL]]<br />
<br />
Experiments with raw bindings to GLFW/OpenGL produced with [[HSFFIG]]<br />
* [http://code.google.com/p/hs-ogl-misc/ hs-ogl-misc]<br />
<br />
== Troubleshooting ==<br />
=== I can't display text with renderString ===<br />
It's probably because the text is displayed too big. Setting a much smaller scale factor before calling renderString should solve the problem.<br />
<haskell><br />
scale 0.001 0.001 (0.001∷GLfloat)<br />
renderString Roman "Test string"<br />
</haskell><br />
=== Animations flicker ===<br />
If you're not using DoubleBuffered display mode, turn that on. Also, you must set the display mode '''before''' creating the window you're going to be drawing in. To check if you've enabled double buffering use something like:<br />
<haskell><br />
db <- get doubleBuffered<br />
</haskell><br />
and set DoubleBuffered mode (before creating your windows!) like this:<br />
<haskell><br />
initialDisplayMode $= [DoubleBuffered]<br />
createWindow "My Window"<br />
</haskell><br />
You will also need to call [http://hackage.haskell.org/packages/archive/GLUT/latest/doc/html/Graphics-UI-GLUT-Window.html#v%3AswapBuffers <haskell>swapBuffers</haskell>] at the end of your draw function.<br />
<br />
=== The depth buffer doesn't work (things that are closer to the camera are occluded by things that are farther from the camera) ===<br />
<br />
Make sure that ''depthFunc'' is set:<br />
<haskell>depthFunc $= Just Less</haskell><br />
<br />
Furthermore, if you're using GLFW, the following var has to be greater than zero:<br />
<haskell>get (windowParam DepthBits)</haskell><br />
<br />
If DepthBits is 0, you probably forgot to initialize the window, like so:<br />
<haskell>openWindow size [DisplayDepthBits 16] Window</haskell><br />
<br />
Once you enable the depth buffer, you will need to clear it before each cycle of your drawing method:<br />
<haskell>clear [ColorBuffer, DepthBuffer]</haskell><br />
<br />
See also: [http://www.opengl.org/resources/faq/technical/depthbuffer.htm#0010 The OpenGL FAQ: 12.010 How do I make depth buffering work?]<br />
<br />
<br />
[[Category:Packages]]<br />
[[Category:Libraries]]</div>Ulfnhttps://wiki.haskell.org/Applications_and_libraries/Compilers_and_interpretersApplications and libraries/Compilers and interpreters2009-04-14T14:15:15Z<p>Ulfn: changed Agda link</p>
<hr />
<div>Haskell, with its support for pattern matching on data structures,<br />
generic structure traversals, and expressive type system, is popular for<br />
implementing compilers and interpreters. Here's a selection of compilers<br />
and interpreters implemented in Haskell.<br />
<br />
==Large languages==<br />
<br />
===Haskell===<br />
<br />
;[http://haskell.org/ghc GHC]<br />
:GHC, The Glasgow Haskell Compiler, is written in Haskell<br />
<br />
;[[Yhc]]<br />
:Yhc, The York Haskell Compiler, is written in Haskell<br />
<br />
;[http://repetae.net/computer/jhc/ Jhc]<br />
:Jhc is a Haskell compiler which aims to produce the most efficient programs possible via whole program analysis<br />
<br />
;[http://haskell.org/nhc98 nhc98]<br />
:A compiler for Haskell 98, written in Haskell<br />
<br />
;[http://www.cs.uu.nl/groups/ST/Ehc/WebHome Ehc]<br />
:The purpose of the EHC project is to provide a description of a Haskell compiler which is as understandable as possible so it can be used for education as well as research.<br />
<br />
;[http://www.csg.lcs.mit.edu/projects/languages/ph.shtml pH]<br />
:A parallel version of Haskell from MIT.<br />
<br />
====Helium====<br />
;[http://www.cs.uu.nl/helium/ Helium]<br />
:A Haskell subset for educational purposes<br />
<br />
====Generic Haskell====<br />
;[http://generic-haskell.org/ Generic Haskell]<br />
:An extension of Haskell that supports generic programming<br />
<br />
====Data Field Haskell====<br />
;[http://www.mrtc.mdh.se/projects/DFH/ Data Field Haskell]<br />
:A dialect of the functional programming language Haskell that provides an instance of data fields<br />
<br />
====Eden====<br />
;[http://www.mathematik.uni-marburg.de/~eden/ Eden]<br />
:A Haskell dialect for parallel programming<br />
<br />
====Chameleon====<br />
;[http://taichi.ddns.comp.nus.edu.sg/taichiwiki/ChameleonHomePage Chameleon]<br />
:A Haskell-style language which implements the ideas described in a ``A Theory of Overloading``<br />
<br />
====CHR (Constraint Handling Rules)====<br />
;[http://www.cs.mu.oz.au/~gjd/haskellchr/ Haskell CHR]<br />
:A concurrent committed-choice constraint logic programming language, implemented using GHC's software transactional memory. According to the site referenced by the above-mentioned link, "It also contains an implementation of WAM for Haskell, so Prolog-style terms with variables are now possible."<br />
<br />
;[http://www.cs.kuleuven.be/~dtai/projects/CHR/systems/stmchr-0.1.tar.gz STM-based CHR implementation, by Michael Stahl] (gzipped TAR file)<br />
<br />
;[http://taichi.ddns.comp.nus.edu.sg/taichiwiki/CCHR CCHR: STM-based CHR implementation by Lam and Sulzmann]<br />
:According to the site referenced by the above-mentioned link, "CCHR is an experimental concurrent implementation of Constraint Handling Rules, designed to exploit concurrency and parallelism explicitly. CCHR is implemented in Haskell, with software transactional memory to manage synchronization of multiple solver threads working on the same problem. Constraint Handling Rules (CHR) is a concurrent committed choice constraint logic programming language to describe transformations (rewritings) among multi-sets of constraints (atomic formulae). CHR naturally support concurrent programming. Conjunction of constraints can be regarded as interacting collections of multiple asynchronous agents or processes. Their interaction is specified via transformation rules which can be applied simultaneously if the transformation rules do not interfere. Hence, one would expect to run CHR faster by executing transformation rules in parallel on a multi-core machine architecture. CCHR exactly allows such concurrency while solving CHR problems and exhibits significant speed up in most problems when executed on multi-core systems."<br />
<br />
===Liskell===<br />
;[http://liskell.org Liskell]<br />
:Liskell is Haskell on the inside but looks like Lisp on the outside<br />
<br />
===Perl===<br />
<br />
;[http://pugscode.org Pugs]<br />
:Pugs is an implementation of Perl 6, written in Haskell. It aims to implement the full Perl6 specification.<br />
<br />
===Python===<br />
<br />
;[http://code.google.com/p/haspy/ haspy]<br />
:Haspy is an implementation of Python in Haskell<br />
<br />
===Ruby===<br />
<br />
;[http://raa.ruby-lang.org/project/rtype/ RType]<br />
:RType is a Ruby interpreter written in Haskell<br />
<br />
===Flapjax===<br />
;[http://www.flapjax-lang.org/ Flapjax]<br />
:Flapjax is a language for functional reactive programming of AJAX web applications, whose compiler ([http://www.flapjax-lang.org/download/flapjax-source.tar.gz source]) is written in Haskell.<br />
<br />
===Scheme===<br />
<br />
;[http://halogen.note.amherst.edu/~jdtang/scheme_in_48/tutorial/overview.html Write Yourself a Scheme in 48 Hours]<br />
:A small Scheme interpreter<br />
<br />
;[http://www.korgwal.com/haskeem/ A Scheme in Haskell]<br />
<br />
===Lisp===<br />
<br />
;[http://www.defmacro.org/ramblings/lisp-in-haskell.html A Lisp Interpreter In Haskell]<br />
:A small lisp interpreter written in Haskell<br />
<br />
=== Emacs Lisp ===<br />
;[http://www.codersbase.com/index.php/helisp Helisp]<br />
:The beginnings of an Emacs lisp compiler/interpreter.<br />
<br />
===Epigram===<br />
<br />
;[http://www.e-pig.org/ Epigram]<br />
:Epigram is a prototype dependently typed functional programming language<br />
<br />
===Curry===<br />
<br />
;[http://danae.uni-muenster.de/~lux/curry/ The M&uuml;nster Curry Compiler]<br />
:A native code compiler for the declarative multi-paradigm language Curry, written in Haskell<br />
<br />
===Bluespec===<br />
;[http://www.bluespec.com Bluespec]<br />
:A compiler for a hardware description language translating a Haskell-like (but with System Verilog syntax these days) language to Verilog.<br />
<br />
===Cayenne===<br />
;[http://www.dependent-types.org/ Cayenne]<br />
:A compiler for a Haskell-like language with dependent types.<br />
<br />
===Agda===<br />
;[http://wiki.portal.chalmers.se/agda/pmwiki.php Agda]<br />
:A Cayenne-like programming language and proof assistant.<br />
<br />
===PolyP===<br />
;[http://www.cs.chalmers.se/~patrikj/poly/polyp/ PolyP]<br />
:A polytypic programming language<br />
<br />
===Forth===<br />
<br />
;[http://feather.perl6.nl/~nothingmuch/harrorth/ Harrorth]<br />
:Harrorth, a Forth interpreter<br />
<br />
===Eiffel===<br />
<br />
;[http://eiffelsoftware.origo.ethz.ch/index.php/DynBindModelHaskell Dynamic binding in Eiffel]<br />
:A model of dynamic binding in ECMA Eiffel, in Haskell<br />
<br />
===Crouton===<br />
<br />
;[http://crouton.sourceforge.net/ Crouton]<br />
:Crouton is a small but fairly complete functional programming language for querying and transforming parsed manuscripts, such as the PPCME. It is intended as an alternative to Corpus Search, based on a different philosophy. It is written in (and largely based on) the very nice functional programming language Haskell using the Parsec library<br />
<br />
=== JavaScript ===<br />
;[http://www.haskell.org/haskellwiki/Libraries_and_tools/HJS HJS]<br />
:HJS is a JavaScript parser written in Haskell. Available from HackageDB.<br />
<br />
===TCL===<br />
;[http://code.google.com/p/hiccup/ Hiccup]<br />
:Hiccup is a minimalistic TCL interpreter. It tries to be relatively simple, relatively efficient, and mostly correct. <br />
<br />
===Smalltalk===<br />
<br />
;[http://code.google.com/p/hst/ hst]<br />
:HST is a Smalltalk implementation in Haskell. [http://lstephen.wordpress.com/2007/07/23/completing-the-spike/ See here for more information]<br />
<br />
=== Disciple ===<br />
;[[DDC]]<br />
:Disciple is an explicitly lazy dialect of Haskell which supports destructive update, computational effects, type directed field projections and some other useful things.<br />
<br />
=== Timber ===<br />
;[http://timber-lang.org/Timber Timber]<br />
:Timber is a modern language for building event-driven systems, based around the notion of reactive objects. It is also a purely functional language derived from Haskell, although with a strict evaluation semantics. The Timber compiler currently runs on Linux and MacOS X platforms, but uses gcc as its back-end so it should be easily portable to most POSIX-like environments.<br />
<br />
<br />
<br />
==Small languages==<br />
<br />
===Baskell===<br />
;[http://www.cs.mu.oz.au/~bjpop/code.html Baskell]<br />
:An interpreter for a small functional programming language. Supports strict and non-strict evaluation, and type inference. Useful for teaching purposes.<br />
<br />
===LambdaPi===<br />
<br />
;[http://www.informatik.uni-bonn.de/~loeh/LambdaPi.html LambdaPi]<br />
:LambdaPi, An Implementation of a Dependently Typed Lambda Calculus<br />
<br />
===Unlambda===<br />
<br />
;[http://www.cse.unsw.edu.au/~dons/code/lambdabot/scripts/Unlambda.hs Unlambda.hs]<br />
:An implementation of Unlambda in Haskell<br />
<br />
===BF===<br />
<br />
;[http://www.cse.unsw.edu.au/~dons/code/lambdabot/scripts/BF.hs BF.hs]<br />
:An implementation of BF in Haskell<br />
<br />
<br />
===Lambda calculus===<br />
<br />
;[http://programming.reddit.com/goto?id=qnir 4 lambda calculus implementations]<br />
:[http://www.augustsson.net/Darcs/Lambda/ With code], by Lennart Augustsson.<br />
<br />
;[http://www.cse.unsw.edu.au/~dons/code/lambdabot/Plugin/Lambda/ LMEngine]<br />
:An implementation of the untyped lambda calculus<br />
<br />
===QML, a functional quantum programming language===<br />
<br />
;[http://sneezy.cs.nott.ac.uk/QML/ QML: A Functional Quantum Programming Language] project<br />
:It is implemented in Haskell.<br />
<br />
:For online material on quantum computing in general, see [http://www.theory.caltech.edu/people/preskill/ph229/ Quantum Computation] course held by [http://www.theory.caltech.edu/people/preskill/index.html John Preskill].<br />
<br />
===HQL - HHM's Quantified Lambda===<br />
<br />
;[http://www.archive.moraldo.com.ar/index.php/Articles/HQLlanguage Hernan's Quantified Lambda]<br />
:a small functional language, whose expressions can involve the use of quantifier operators<br />
<br />
===Atom===<br />
;[http://funhdl.org/wiki/doku.php/atom Atom]<br />
:Atom is a small HDL that compiles conditional term rewriting systems down to Verilog RTL.<br />
<br />
===AL (Assignment Language)===<br />
<br />
:It is used for teaching purposes in at the Technical University of Vienna.<br />
:An interpreter implemented in Haskell is described in [http://www.logic.at/staff/robinson/ali.ps ALI - an AL Interpreter implemented in Haskell] written by Peter Robinson.<br />
<br />
=== Whitespace ===<br />
;[http://compsoc.dur.ac.uk/whitespace/index.php Whitespace]<br />
:A language that uses whitespace characters as language elements and ignores all non-whitespace characters<br />
<br />
=== LIPL ===<br />
;[http://www.lipl.googlepages.com/index.html LIPL]<br />
:An interpreter for a tiny functional programming language. It features Hindley-Milner style type inference.<br />
<br />
<br />
<br />
== Embedded languages ==<br />
<br />
=== ForSyDe ===<br />
The ForSyDe (Formal System Design) methodology has been developed with the objective to move system-on-chip design to a higher level of abstraction. ForSyDe is implemented as a Haskell-embedded behavioral DSL.<br />
<br />
<br />
<br />
<br />
== Debuggers ==<br />
<br />
;[http://www.dsic.upv.es/users/elp/debussy Debussy]<br />
:A declarative debugger for OBJ-like languages<br />
<br />
;See also [[Debugging]].<br />
<br />
{{LibrariesPage}}</div>Ulfnhttps://wiki.haskell.org/User:UlfnUser:Ulfn2008-07-29T08:23:24Z<p>Ulfn: </p>
<hr />
<div>I'm a post doc at Chalmers University of Technology [http://www.cs.chalmers.se/~ulfn].</div>Ulfnhttps://wiki.haskell.org/Implement_a_chat_serverImplement a chat server2007-11-12T23:53:34Z<p>Ulfn: fixed a minor bug</p>
<hr />
<div>[[Category:Tutorials]]<br />
[[Category:Code]]<br />
== Introduction ==<br />
This page describes how to implement a simple chat server. The server should support multiple connected users. Messages sent to the server are broadcast to all currently connected users.<br />
<br />
== Trivial server ==<br />
We start with a trivial server.<br />
<haskell><br />
import Network.Socket<br />
<br />
main :: IO ()<br />
main = do<br />
-- create socket<br />
sock <- socket AF_INET Stream 0<br />
-- make socket immediately reusable - eases debugging.<br />
setSocketOption sock ReuseAddr 1<br />
-- listen on TCP port 4242<br />
bindSocket sock (SockAddrInet 4242 iNADDR_ANY)<br />
-- allow a maximum of 2 outstanding connections<br />
listen sock 2<br />
mainLoop sock<br />
<br />
mainLoop :: Socket -> IO ()<br />
mainLoop sock = do<br />
-- accept one connection and handle it<br />
conn <- accept sock<br />
runConn conn<br />
mainLoop sock<br />
<br />
runConn :: (Socket, SockAddr) -> IO ()<br />
runConn (sock, _) = do<br />
send sock "Hi!\n"<br />
sClose sock<br />
</haskell><br />
<br />
This server creates a socket for listening on port 4242, and sends a single<br />
line to everyone who connects.<br />
<br />
== Using System.IO for sockets ==<br />
<hask>System.IO</hask> functions for input and output are much more convenient than those that <hask>Network.Socket</hask> provides. We can turn a <hask>Socket</hask> into a <hask>Handle</hask> as follows:<br />
<br />
<haskell><br />
import System.IO<br />
[...]<br />
runConn (sock, _) = do<br />
hdl <- socketToHandle sock ReadWriteMode<br />
hSetBuffering hdl NoBuffering<br />
putStrLn hdl "Hi!"<br />
hClose hdl<br />
</haskell><br />
<br />
== Concurrency ==<br />
So far the server can only handle one connection at a time. This is ok for just writing a message but won't work for a chat server. We can fix this quite easily though, using <hask>forkIO</hask>:<br />
<br />
<haskell><br />
import Control.Concurrent<br />
[...]<br />
mainLoop sock = do<br />
conn <- accept sock<br />
forkIO (runConn conn)<br />
mainLoop sock<br />
</haskell><br />
<br />
== Adding communication between threads ==<br />
This seems to be a hard problem. Luckily, the <hask>Control.Concurrent.Chan</hask> module provides exactly what we need: channels with a single write and multiple read ends. First we decide on a message type. Let's use a string for now:<br />
<br />
<haskell><br />
type Msg = String<br />
</haskell><br />
<br />
<hask>main</hask> will have to create a channel, and pass it to <hask>mainLoop</hask>.<br />
<br />
<haskell><br />
import Control.Concurrent.Chan<br />
[...]<br />
main = do<br />
[...]<br />
chan <- newChan<br />
mainLoop sock chan<br />
</haskell><br />
<br />
<hask>mainLoop</hask> in turn will pass it to <hask>runConn</hask>.<br />
<br />
<haskell><br />
mainLoop :: Socket -> Chan Msg -> IO ()<br />
mainLoop sock chan = do<br />
conn <- accept sock<br />
forkIO (runConn conn chan nr)<br />
mainLoop sock chan<br />
</haskell><br />
<br />
And finally, <hask>runConn</hask> will duplicate the channel and read from it.<br />
<br />
<haskell><br />
import Control.Monad<br />
import Control.Monad.Fix (fix)<br />
[...]<br />
runConn :: (Socket, SockAddr) -> Chan Msg -> -> IO ()<br />
runConn (sock, _) chan = do<br />
let broadcast msg = writeChan chan msg<br />
hdl <- socketToHandle sock ReadWriteMode<br />
hSetBuffering hdl NoBuffering<br />
chan' <- dupChan chan<br />
-- fork off thread for reading from the duplicated channel<br />
forkIO $ fix $ \loop -> do<br />
line <- readChan chan'<br />
hPutStrLn hdl line<br />
loop<br />
-- read lines from socket and echo them back to the user<br />
fix $ \loop -> do<br />
line <- liftM init (hGetLine hdl)<br />
broadcast line<br />
loop<br />
</haskell><br />
<br />
Note that <hask>runConn</hask> now actually forks another worker thread for sending messages to the connected user.<br />
<br />
== Cleanups and final code ==<br />
[[Image:chat_server_screenshot.png|thumb|Screenshot :)]]<br />
There are two major problems left in the code. First, the code has a memory leak, because the original channel is never read by anyone. This can be fixed by adding another thread just for that purpose.<br />
<br />
Secondly, closing connections is not handled gracefully at all. This requires exception handling.<br />
<br />
The code below fixes the first issue and mostly fixes the second one, and adds a few cosmetic improvements:<br />
<br />
* messages are not echoed back to the user they came from.<br />
* every connection is associated with a name.<br />
<br />
<haskell><br />
-- with apologies for the lack of comments :)<br />
<br />
import Network.Socket<br />
import System.IO<br />
import Control.Exception<br />
import Control.Concurrent<br />
import Control.Concurrent.Chan<br />
import Control.Monad<br />
import Control.Monad.Fix (fix)<br />
<br />
type Msg = (Int, String)<br />
<br />
main :: IO ()<br />
main = do<br />
chan <- newChan<br />
sock <- socket AF_INET Stream 0<br />
setSocketOption sock ReuseAddr 1<br />
bindSocket sock (SockAddrInet 4242 iNADDR_ANY)<br />
listen sock 2<br />
forkIO $ fix $ \loop -> do<br />
(_, msg) <- readChan chan<br />
loop<br />
mainLoop sock chan 0<br />
<br />
mainLoop :: Socket -> Chan Msg -> Int -> IO ()<br />
mainLoop sock chan nr = do<br />
conn <- accept sock<br />
forkIO (runConn conn chan nr)<br />
mainLoop sock chan $! nr+1<br />
<br />
runConn :: (Socket, SockAddr) -> Chan Msg -> Int -> IO ()<br />
runConn (sock, _) chan nr = do<br />
let broadcast msg = writeChan chan (nr, msg)<br />
hdl <- socketToHandle sock ReadWriteMode<br />
hSetBuffering hdl NoBuffering<br />
hPutStrLn hdl "Hi, what's your name?"<br />
name <- liftM init (hGetLine hdl)<br />
broadcast ("--> " ++ name ++ " entered.")<br />
hPutStrLn hdl ("Welcome, " ++ name ++ "!")<br />
chan' <- dupChan chan<br />
reader <- forkIO $ fix $ \loop -> do<br />
(nr', line) <- readChan chan'<br />
when (nr /= nr') $ hPutStrLn hdl line<br />
loop<br />
handle (\_ -> return ()) $ fix $ \loop -> do<br />
line <- liftM init (hGetLine hdl)<br />
case line of<br />
"quit" -> hPutStrLn hdl "Bye!"<br />
_ -> do<br />
broadcast (name ++ ": " ++ line)<br />
loop<br />
killThread reader<br />
broadcast ("<-- " ++ name ++ " left.")<br />
hClose hdl<br />
</haskell><br />
<br />
Have fun chatting!</div>Ulfnhttps://wiki.haskell.org/Dependent_typeDependent type2007-10-09T14:20:59Z<p>Ulfn: </p>
<hr />
<div>__TOC__<br />
<br />
== The concept of dependent types ==<br />
<br />
=== General ===<br />
<br />
* [http://en.wikipedia.org/wiki/Dependent_types Wikipedia]<br />
* [http://www-sop.inria.fr/oasis/Caminha00/abstract.html Dependent Types in Programming] abstract in APPSEM'2000<br />
* [http://www.brics.dk/RS/01/10/BRICS-RS-01-10.ps.gz Do we need dependent types?] by Daniel Fridlender and Mia Indrika, 2001.<br />
<br />
<br />
=== Type theory ===<br />
<br />
Simon Thompson: [http://www.cs.kent.ac.uk/people/staff/sjt/TTFP/ Type Theory and Functional Programming]. Section 6.3 deals with dependent types, but because of the strong emphasis on [http://en.wikipedia.org/wiki/Curry_Howard_isomorphism Curry-Howard isomorphism] and the connections between logic and programming,<br />
the book seemed cathartic for me even from its beginning.<br />
<br />
Another interesting approach to Curry-Howard isomorphism and the concept of dependent type: [http://www.cs.chalmers.se/~aarne/course-langtech/lectures/lang09.html Lecture 9. Semantics and pragmatics of text and dialogue] dicsusses these concepts in the context of linguistics. Written by [http://www.cs.chalmers.se/~aarne/ Arne Ranta], see also [[Libraries and tools/Linguistics#Other functional or Haskell-related approaches to linguistics|his online course and other linguistical materials on the Linguistics wikipage]].<br />
<br />
[http://lists.seas.upenn.edu/mailman/listinfo/types-list Types Forum]<br />
<br />
=== Illative combinatory logic ===<br />
<br />
To see how Illative [[Combinatory logic]] deals with dependent types, see combinator '''G''' described in [http://citeseer.ist.psu.edu/246934.html Systems of Illative Combinatory Logic complete for first-order propositional and predicate calculus] by Henk Barendregt, Martin Bunder, Wil Dekkers.<br />
It seems to me that the dependent type construct<br />
<math>\forall x : S \Rightarrow T</math><br />
of Epigram corresponds to<br />
<math>\mathbf G\;S\;(\lambda x . T)</math><br />
in Illative Combinatory Logic. I think e.g. the followings should correspond to each other:<br />
* <math>\mathrm{realNullvector} :\;\;\;\forall n: \mathrm{Nat} \Rightarrow \mathrm{RealVector}\;n</math><br />
* <math>\mathbf G\;\,\mathrm{Nat}\;\,\mathrm{RealVector}\;\,\mathrm{realNullvector}</math><br />
<br />
<br />
== Dependently typed languages ==<br />
<br />
=== Epigram ===<br />
<br />
[http://www.e-pig.org/ Epigram] is a full dependently typed programming language, see especially<br />
* [http://www.e-pig.org/downloads/epigram-notes.pdf Epigram Tutorial] by Conor McBride<br />
* and [http://www.e-pig.org/downloads/ydtm.pdf Why dependent types matter] by Thorsten Altenkirch, Conor McBride and James McKinna).<br />
<br />
Dependent types (of this language) also provide a not-forgetful concept of '''views''' (already mentioned in the Haskell [[Future of Haskell#Extensions of Haskell]];<br />
the connection between these concepts is described in p. 32 of Epigram Tutorial (section ''4.6 Patterns Forget; Matching Is Remembering'').<br />
<br />
See Epigram also as [[Libraries and tools/Theorem provers|theorem prover]].<br />
<br />
=== Agda ===<br />
<br />
[http://www.cs.chalmers.se/~ulfn/Agda/ Agda] is a system for incrementally developing proofs and programs. Agda is also a functional language with dependent types. This language is similar to Epigram but has a more Haskell-like syntax.<br />
<br />
People who are interested also in theorem proving may see the [[Libraries and tools/Theorem provers|theorem provers]] page.<br />
<br />
=== Cayenne ===<br />
<br />
[http://www.cs.chalmers.se/~augustss/cayenne/index.html Cayenne] is influenced also by constructive type theory (see its page).<br />
<br />
Dependent types make it possible not to have a separate module lenguage and a core language. This idea may concern Haskell too, see [[First-class module]] page.<br />
<br />
Depandent types make it useful also as a [[Libraries and tools/Theorem provers|theorem prover]].<br />
<br />
=== Qi ===<br />
<br />
[http://www.lambdassociates.org/ Qi] is a Lisp-based functional programming language. It provides many possibilities (currying, pattern matching, type checking etc.), and it uses sequent calculus notation for defining new types. This enables [http://www.lambdassociates.org/advtypes.htm a very powerful type system].<br />
<br />
=== Other techniques ===<br />
<br />
Also [http://www.defmacro.org/blaise/faq.html Blaise] is a Lisp-based language with dependent types. It will be released under GPL, but has not yet a released implementation.<br />
<br />
[http://www-sop.inria.fr/oasis/DTP00/ APPSEM Workshop on Subtyping & Dependent Types in Programming]<br />
<br />
== Dependent types in Haskell programming ==<br />
<br />
=== Lightweight Dependent Typing ===<br />
[http://pobox.com/~oleg/ftp/Computation/lightweight-dependent-typing.html This web page] describes the lightweight approach<br />
and its applications, e.g., statically safe head/tail functions and<br />
the elimination<br />
of array bound check (even in such complex algorithms as Knuth-Morris-Pratt<br />
string search). The page also briefly describes `singleton types' (Hayashi and<br />
Xi).<br />
<br />
=== Library ===<br />
<br />
[http://www.dcs.st-and.ac.uk/~eb/ivor.php Ivor] is type theory based theorem proving library -- written by [http://www.dcs.st-and.ac.uk/~eb/index.php Edwin Brady] (see also the author's homepage, there are a lot of materials concerning dependent type theory there).<br />
<br />
=== Proposals ===<br />
John Hughes: [http://www.coverproject.org/TalksUntilSpring2004/DependentTypesInHaskell.pdf Dependent Types in Haskell (some ideas)].<br />
<br />
=== Simulating them ===<br />
* [http://haskell.org/hawiki/SimulatingDependentTypes SimulatingDependentTypes] of HaWiki<br />
* The [[Type#See also|''See also'' section of Type]] page contains links to many related idioms. Especially [[type arithmetic]] seems to me also a way yielding some tastes from dependent type theory.<br />
* On the usefulness of such idioms in practice, see HaskellDB's pages<br />
** [http://haskelldb.sourceforge.net/ updated] page (see ''Papers'' subsection on [http://haskelldb.sourceforge.net/#documentation Documentation])<br />
** which presupposes reading also paper on the [http://www.haskell.org/haskellDB/ original] page (see [http://www.haskell.org/haskellDB/doc.html Documentation subpage], PostScript version)<br />
<br />
[[Category:Theoretical foundations]]<br />
<br />
[[Category:Type-level programming]]</div>Ulfnhttps://wiki.haskell.org/Dependent_typeDependent type2007-10-09T14:19:45Z<p>Ulfn: Updated link to Agda</p>
<hr />
<div>__TOC__<br />
<br />
== The concept of dependent types ==<br />
<br />
=== General ===<br />
<br />
* [http://en.wikipedia.org/wiki/Dependent_types Wikipedia]<br />
* [http://www-sop.inria.fr/oasis/Caminha00/abstract.html Dependent Types in Programming] abstract in APPSEM'2000<br />
* [http://www.brics.dk/RS/01/10/BRICS-RS-01-10.ps.gz Do we need dependent types?] by Daniel Fridlender and Mia Indrika, 2001.<br />
<br />
<br />
=== Type theory ===<br />
<br />
Simon Thompson: [http://www.cs.kent.ac.uk/people/staff/sjt/TTFP/ Type Theory and Functional Programming]. Section 6.3 deals with dependent types, but because of the strong emphasis on [http://en.wikipedia.org/wiki/Curry_Howard_isomorphism Curry-Howard isomorphism] and the connections between logic and programming,<br />
the book seemed cathartic for me even from its beginning.<br />
<br />
Another interesting approach to Curry-Howard isomorphism and the concept of dependent type: [http://www.cs.chalmers.se/~aarne/course-langtech/lectures/lang09.html Lecture 9. Semantics and pragmatics of text and dialogue] dicsusses these concepts in the context of linguistics. Written by [http://www.cs.chalmers.se/~aarne/ Arne Ranta], see also [[Libraries and tools/Linguistics#Other functional or Haskell-related approaches to linguistics|his online course and other linguistical materials on the Linguistics wikipage]].<br />
<br />
[http://lists.seas.upenn.edu/mailman/listinfo/types-list Types Forum]<br />
<br />
=== Illative combinatory logic ===<br />
<br />
To see how Illative [[Combinatory logic]] deals with dependent types, see combinator '''G''' described in [http://citeseer.ist.psu.edu/246934.html Systems of Illative Combinatory Logic complete for first-order propositional and predicate calculus] by Henk Barendregt, Martin Bunder, Wil Dekkers.<br />
It seems to me that the dependent type construct<br />
<math>\forall x : S \Rightarrow T</math><br />
of Epigram corresponds to<br />
<math>\mathbf G\;S\;(\lambda x . T)</math><br />
in Illative Combinatory Logic. I think e.g. the followings should correspond to each other:<br />
* <math>\mathrm{realNullvector} :\;\;\;\forall n: \mathrm{Nat} \Rightarrow \mathrm{RealVector}\;n</math><br />
* <math>\mathbf G\;\,\mathrm{Nat}\;\,\mathrm{RealVector}\;\,\mathrm{realNullvector}</math><br />
<br />
<br />
== Dependently typed languages ==<br />
<br />
=== Epigram ===<br />
<br />
[http://www.e-pig.org/ Epigram] is a full dependently typed programming language, see especially<br />
* [http://www.e-pig.org/downloads/epigram-notes.pdf Epigram Tutorial] by Conor McBride<br />
* and [http://www.e-pig.org/downloads/ydtm.pdf Why dependent types matter] by Thorsten Altenkirch, Conor McBride and James McKinna).<br />
<br />
Dependent types (of this language) also provide a not-forgetful concept of '''views''' (already mentioned in the Haskell [[Future of Haskell#Extensions of Haskell]];<br />
the connection between these concepts is described in p. 32 of Epigram Tutorial (section ''4.6 Patterns Forget; Matching Is Remembering'').<br />
<br />
See Epigram also as [[Libraries and tools/Theorem provers|theorem prover]].<br />
<br />
=== Agda ===<br />
<br />
“[http://www.cs.chalmers.se/~ulfn/Agda/ Agda] is a system for incrementally developing proofs and programs. Agda is also a functional language with dependent types. This language is similar to Epigram but has a more Haskell-like syntax.“<br />
<br />
People who are interested also in theorem proving may see the [[Libraries and tools/Theorem provers|theorem provers]] page.<br />
<br />
=== Cayenne ===<br />
<br />
[http://www.cs.chalmers.se/~augustss/cayenne/index.html Cayenne] is influenced also by constructive type theory (see its page).<br />
<br />
Dependent types make it possible not to have a separate module lenguage and a core language. This idea may concern Haskell too, see [[First-class module]] page.<br />
<br />
Depandent types make it useful also as a [[Libraries and tools/Theorem provers|theorem prover]].<br />
<br />
=== Qi ===<br />
<br />
[http://www.lambdassociates.org/ Qi] is a Lisp-based functional programming language. It provides many possibilities (currying, pattern matching, type checking etc.), and it uses sequent calculus notation for defining new types. This enables [http://www.lambdassociates.org/advtypes.htm a very powerful type system].<br />
<br />
=== Other techniques ===<br />
<br />
Also [http://www.defmacro.org/blaise/faq.html Blaise] is a Lisp-based language with dependent types. It will be released under GPL, but has not yet a released implementation.<br />
<br />
[http://www-sop.inria.fr/oasis/DTP00/ APPSEM Workshop on Subtyping & Dependent Types in Programming]<br />
<br />
== Dependent types in Haskell programming ==<br />
<br />
=== Lightweight Dependent Typing ===<br />
[http://pobox.com/~oleg/ftp/Computation/lightweight-dependent-typing.html This web page] describes the lightweight approach<br />
and its applications, e.g., statically safe head/tail functions and<br />
the elimination<br />
of array bound check (even in such complex algorithms as Knuth-Morris-Pratt<br />
string search). The page also briefly describes `singleton types' (Hayashi and<br />
Xi).<br />
<br />
=== Library ===<br />
<br />
[http://www.dcs.st-and.ac.uk/~eb/ivor.php Ivor] is type theory based theorem proving library -- written by [http://www.dcs.st-and.ac.uk/~eb/index.php Edwin Brady] (see also the author's homepage, there are a lot of materials concerning dependent type theory there).<br />
<br />
=== Proposals ===<br />
John Hughes: [http://www.coverproject.org/TalksUntilSpring2004/DependentTypesInHaskell.pdf Dependent Types in Haskell (some ideas)].<br />
<br />
=== Simulating them ===<br />
* [http://haskell.org/hawiki/SimulatingDependentTypes SimulatingDependentTypes] of HaWiki<br />
* The [[Type#See also|''See also'' section of Type]] page contains links to many related idioms. Especially [[type arithmetic]] seems to me also a way yielding some tastes from dependent type theory.<br />
* On the usefulness of such idioms in practice, see HaskellDB's pages<br />
** [http://haskelldb.sourceforge.net/ updated] page (see ''Papers'' subsection on [http://haskelldb.sourceforge.net/#documentation Documentation])<br />
** which presupposes reading also paper on the [http://www.haskell.org/haskellDB/ original] page (see [http://www.haskell.org/haskellDB/doc.html Documentation subpage], PostScript version)<br />
<br />
[[Category:Theoretical foundations]]<br />
<br />
[[Category:Type-level programming]]</div>Ulfnhttps://wiki.haskell.org/User:UlfnUser:Ulfn2006-12-12T09:18:09Z<p>Ulfn: </p>
<hr />
<div>I'm a PhD student at Chalmers University of Technology [http://www.cs.chalmers.se/~ulfn].</div>Ulfnhttps://wiki.haskell.org/Haskell_Quiz/CountdownHaskell Quiz/Countdown2006-11-30T14:03:39Z<p>Ulfn: added Graham Huttons JFP paper to the solutions</p>
<hr />
<div>This question was based on a UK game show. Given a target number, a set of source numbers which may be used at most once, and the 4 basic arithmetic operators (+, -, *, /), construct the whole number closest to the target.<br />
<br />
==The Problem==<br />
<br />
* http://www.rubyquiz.com/quiz7.html<br />
<br />
==Solutions==<br />
<br />
* [http://www.cs.nott.ac.uk/~gmh/bib.html#countdown Graham Hutton] (JFP paper)<br />
* [[Haskell Quiz/Countdown/Solution Dolio|Dan Doel]]</div>Ulfnhttps://wiki.haskell.org/Haskell_Quiz/Secret_Santas/Solution_MatthiasHaskell Quiz/Secret Santas/Solution Matthias2006-11-30T13:54:50Z<p>Ulfn: </p>
<hr />
<div>[[Category:Code]]<br />
<br />
this program takes embarassingly long to answer, even for the seven people from the puzzle. but writing it down was easy. rather than computing all results and picking a random one, i think function f should shuffle santas and victims, and then take the first valid solution returned by q. this here works, though, so i'll bail out.<br />
<br />
note that the algorithm itself, without parsing, output, and selection of a random solution, takes only 16 short lines, comments and type signatures included!<br />
<br />
<haskell><br />
module Main where<br />
import Monad<br />
import List<br />
import Random<br />
<br />
data P = P String String String deriving (Show, Eq, Ord)<br />
<br />
parseP :: String -> P<br />
parseP s = f "" s<br />
where<br />
f acc (' ':s) = case g "" s of (lastname, email) -> P (reverse acc) lastname email<br />
f acc (c:s) = f (c:acc) s<br />
<br />
g acc (' ':s) = (reverse acc, s)<br />
g acc (c:s) = g (c:acc) s<br />
<br />
showPs :: [(P, P)] -> String<br />
showPs = join . map (\ (santa, victim) -> show santa ++ " is secrect santa for " ++ show victim ++ "\n")<br />
<br />
main :: IO ()<br />
main = getContents >>= g >>= putStr . showPs<br />
<br />
g :: String -> IO [(P, P)] -- parse input<br />
g i = let k = map parseP $ lines i in f k k<br />
<br />
f :: [P] -> [P] -> IO [(P, P)] -- compute output<br />
f santas victims = do<br />
let all = q [] santas victims<br />
i <- randomRIO (0, length all - 1)<br />
return (all !! i)<br />
<br />
-- q takes a partial solution, a pool of remaining santas, and a pool of remaining victims. it then produces all<br />
-- possible next matches, calls itself recursively, and returns the complete set of all solutions.<br />
<br />
q :: [(P, P)] -> [P] -> [P] -> [[(P, P)]]<br />
q acc [] [] = [acc] -- (found a valid solution)<br />
q acc [] _ = [] -- leftover victims<br />
q acc _ [] = [] -- leftover santas<br />
q acc santas victims = [ tl | santa <- santas,<br />
victim <- victims,<br />
matchOk santa victim,<br />
tl <- q ((santa, victim) : acc)<br />
(santas \\ [santa])<br />
(victims \\ [victim]) ]<br />
<br />
matchOk :: P -> P -> Bool<br />
matchOk (P _ santa _) (P _ victim _) = santa /= victim<br />
</haskell><br />
<br />
----<br />
<br />
Note that the reason this algorithm takes so long is that it's generating every permutation of the santa/victim list, even though many are the same except for the order. With two people, for example, you'll get:<br />
<haskell><br />
[ [(A,B),(B,A)], [(B,A),(A,B)] ]<br />
</haskell><br />
These two are the same list, since the order is not significant. The algorithm can be made efficient by choosing a "canonical" ordering for the pair list, and skipping permutations that are not in that order.<br />
<br />
For example, make sure the new pair is "less" than the top pair before adding it to the list of possibilities:<br />
<haskell><br />
q :: [(P, P)] -> [P] -> [P] -> [[(P, P)]]<br />
q acc [] [] = [acc] -- (found a valid solution)<br />
q acc [] _ = [] -- leftover victims<br />
q acc _ [] = [] -- leftover santas<br />
q acc santas victims = [ tl | santa <- santas,<br />
victim <- victims,<br />
matchOk santa victim,<br />
null acc || (santa, victim) <= (head acc), -- change<br />
tl <- q ((santa, victim) : acc)<br />
(santas \\ [santa])<br />
(victims \\ [victim]) ]<br />
</haskell><br />
--[[User:Kelan|Kelan]] 20:41, 30 October 2006 (UTC)<br />
<br />
Even simpler is to generate the pairs in the right order from the start:<br />
<haskell><br />
q :: [P] -> [P] -> [[(P, P)]]<br />
q [] [] = [[]]<br />
q (santa : santas) victims =<br />
[ (santa, victim) : rest<br />
| victim <- victims<br />
, matchOk santa victim<br />
, rest <- q santas (delete victim victims)<br />
]<br />
</haskell><br />
Note that if the number of santas are the same as the number of victims we don't need the clauses for leftover santas/victims.<br />
<br />
[[User:Ulfn|Ulfn]] 13:54, 30 November 2006 (UTC)</div>Ulfn