[Haskell-cafe] About code style ?
Gregory Crosswhite
gcross at phys.washington.edu
Tue Feb 2 02:43:56 EST 2010
Ditto what everyone else has said. But to clarify what's going on:
The braces are used to introduce a list of "things", such as monadic actions, data fields, or declarations. For example, consider the following code:
f a =
let {
a_times_2 = a*2;
a_times_4 = a*4;
} in a_times_2+a_times_4
main = putStrLn $ "f 3 = " ++ show (f 3)
The reason why my code compiled and yours didn't is because the compiler saw that the braces were being used to introduce a list of declarations, and the reason why it knew this was because of the "let" keyword. By contrast, in your code it doesn't see a "let", so it assumes that you must be introducing a list of monadic actions. Hence it yells at you for not putting in a "do".
Remember that a pure function is merely a definition of what the output is for a given input. It does not say anything about *how* to do this. Thus, you should never think of a pure function as being a list of actions but rather (approximately) a definition which may require some additional declarations (such as introduced by "let") solely for the purpose of making it easier for *you* to *express* what its value is. (I say approximately because the way you express it does affect the way it gets computed despite technically being pure, but this is not something you should be worrying about right now.)
But again, even though you could use curly brackets and semicolons as I illustrated above, you really should be using whitespace as it is the standard practice; others reading your code may be confused by their presence and so have to work harder to figure out what is going on.
Cheers,
Greg
On Feb 1, 2010, at 6:22 PM, zaxis wrote:
>
> For me i like C style instead of layout. For example,
> func1 a = do
> -- ...
> a * 2
> -- ...
>
> I always write it as:
> func1 a = do {
> -- ...;
> a * 2;
> -- ...;
> }
>
> However, i donot know how to write pure function using C style.
> func1 a = {
> -- ...;
> a * 2;
> -- ...;
> }
>
> will not compile without `do`.
>
> Sincerely!
>
> -----
> fac n = foldr (*) 1 [1..n]
> --
> View this message in context: http://old.nabble.com/About-code-style---tp27414627p27414627.html
> Sent from the Haskell - Haskell-Cafe mailing list archive at Nabble.com.
>
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe
More information about the Haskell-Cafe
mailing list