Your First Haskell Function
- Haskell
- Lautaro Lobo
- 02 May, 2019
Your first Haskell function. Who would say that you would come this far, ah.
A function takes some parameters and shows up an output, after a computational process that used the parameters in some way.
The function that we are going to define today, since it’s the first one, will be basic. You will give it two numbers and it’ll sum them, giving you back a single number. But, what kind of number? Any number? Actually not, this function will work with just Integers. You will clarifiy this by writing the type of the function.
The first thing that you should know about writing functions in Haskell, is that you should always define the type of the function before you define the function itself, if you don’t define it, Haskell will figure out which type is the best to match with your function, most of the time it will figure it out right, but some times may miss match the inferenced type and your function won’t work.
sumBoth :: Int -> Int -> Int
We defined the type; it takes one Integer, then another Integer, and the output will be an Integer, great. You may have noticed that I named the function “sumBoth”, this is because it’s important that the function’s name tells you what that particular function does and also, the name should be short, so when you call it you won’t waste much time writing it. It may seem a silly advise but trust me, getting used to good practices will save you tons of bugs.
Now, the function definition:
sumBoth x y = x + y
And that’s it! Now save your file with .hs extension, and then open up the terminal, we will test this function there. Go to the directory where you saved your file and simply write
ghci
You’ll see something like this:
GHCi, version x.y.z: http://www.haskell.org/ghc/ :? for help
Prelude>
There write
:load filename.hs
And this should show up:
[1 of 1] Compiling Main ( filename.hs, interpreted )
Ok, modules loaded: Main.
*Main>
Then call sumBoth and in the line below you’ll see the result:
*Main> sumBoth 5 4
9
Something went wrong? Please tell me and I’ll be glad to help you out!
Want to try the next level? Go ahead!