Learn Haskell in 10 minutes
Haskell is a functional (that is, everything is done with function calls), statically, implicitly typed (types are checked by the compiler, but you don't have to declare them), lazy (nothing is done until it needs to be) language. It's closest popular relative is probably the ML family of languages.
The most common Haskell compiler is GHC. You can download GHC from http://www.haskell.org/ghc/download_ghc_661.html. GHC binaries are available for Linux, FreeBSD, MacOS, Windows, and Solaris. Once you've installed GHC, you get two programs you're interested in right now: ghc, and ghci. The first compiles Haskell libraries or applications to binary code. The second is an interpreter that lets you write Haskell code and get feedback right away.
2 Simple Expressions
You can type most math expressions directly into ghci and get an answer.Prelude>
16Strings are in "double quotes." You can concatenate them with
Calling functions is done by putting the arguments directly after the function. There are no parentheses as part of the function call:Prelude>
3 The Console
I/O actions can be used to read from and write to the console. Some common ones include:Prelude>
2 + 2 = 4Prelude>
ABCDE 12345Reading can be done with
(The 4 was input. The 16 was a result.)There is actually another way to write
main = do putStrLn "What is 2 + 2?" x <- readLn if x == 4 then putStrLn "You're right!" else putStrLn "You're wrong!"
4 Simple TypesSo far, not a single type declaration has been mentioned. That's because Haskell does type inference. You generally don't have to declare types unless you want to. If you do want to declare types, you use
You can also ask ghci what type it has chosen for something. This is useful because you don't generally have to declare your types.Prelude> :t
Things get more interesting for numbers.Prelude> :t
These type signatures mean:
- can be used as any numeric type. (This is why I was able to declare42can be any fractional type, but not an integral type.5<hask> as either an Int or a Double earlier.)
- (which is a function call, incidentally) can be any integral type, but not a fractional type.gcd 15 20
There are five numeric types in the Haskell "prelude" (the part of the library you get without having to import anything):
- is an integer with at least 30 bits of precision.Int
- is an integer with unlimited precision.Integer
- is a single precision floating point number.Float
- is a double precision floating point number.Double
- type class. The first two belong toRational<hask> is a fraction type, with no rounding error.
All five of these belong to the <hask>Num, and the last two toIntegral.Fractional
Putting it all together,Prelude>
<interactive>:1:0: No instance for (Integral Double)The final type worth mentioning here is