Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!uunet!mcsun!ukc!strath-cs!cs.glasgow.ac.uk!kh From: kh@cs.glasgow.ac.uk (Kevin Hammond) Newsgroups: comp.lang.functional Subject: Re: "Off-side rule" Message-ID: <7415@vanuata.cs.glasgow.ac.uk> Date: 14 Jan 91 19:48:38 GMT References: <22307@rouge.usl.edu> <1991Jan10.111559.12440@odin.diku.dk> <293@smds.UUCP> Reply-To: kh@cs.glasgow.ac.uk (Kevin Hammond) Organization: Comp Sci, Glasgow Univ, Scotland Lines: 93 In article <293@smds.UUCP> rh@smds.UUCP (Richard Harter) writes: >In article , acha@CS.CMU.EDU (Anurag Acharya) writes: >> What is the justification for this "off-side" rule ? The idea of whitespace >> having semantics is a potential source of inscrutable bugs and, frankly >> speaking, seems to go against the grain of modern programming language >> design. This is to some extent true of Miranda, but it is less true of Haskell (also mentioned in this thread). The advantage of the approach is that programmers usually treat white-space as if it were significant (vide Pascal programs laid out a line at a time). Capitalising on this tendency helps improve legibility and conciseness, while permitting a certain flexibility in layout. Compare: f 0 = 1 f n = n * f (n-1) main = print(f 100) with: module Main(main) where { f 0 = 1; f n = n * f (n-1); main = print(f 100) } The improvement is rather better with local definitions and longer programs (I'm using Haskell here, Miranda modules have shorter headers). >Could some one post a summary explanation of the off-side rule, please? Simply put, in Miranda all text to the right of a defining operator ("where" or "=") after a newline comprises part of the previous line. Other newlines act as separators. This applies recursively, so you can build up levels of nested definitions structured by their layout. This allows: || Example 1 f x = g + h where g = fac x h = x * 2 || Example 2 f (x:xs) y z = x + y + z g = 100 etc. (The latter is an example of how *not* to use the off-side rule!) Note that Haskell's layout rule is *not identical* to the Miranda off-side rule. In particular: i) It is possible to turn off layout at will; ii) The layout rules do not use "=" as a defining point; iii) Alignment of definitions is significant (ii) is particularly important -- I find my Miranda programs regularly vanish off the RHS of the page (because of the need to insert a fixed amount of space), but this never happens with Haskell. It is also easier to avoid off-side errors in Haskell (to the extent that these almost never occur, even when porting free-form programs). As illustration: f x = g + h where g = fac x h = x * 2 is legal Haskell, but not legal Miranda (the "where" is off-side with respect to the first "="). The Haskell layout rule is fully described in the Haskell report (section 1.5, page 3). I'll post it if there's enough interest (5-6 paragraphs including explanation). Kevin -- This Signature Intentionally Left Blank. E-mail: kh@cs.glasgow.ac.uk