-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfunctions.hs
59 lines (44 loc) · 2.17 KB
/
functions.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
-- # http://learnyouahaskell.com/starting-out#babys-first-functions
-- LOAD THIS FILE WITH ":l functions" within repl (ghci)
-- and reload with ":r"
-- In Haskell functions are lazy!
-- Functions can't begin with uppercase letters.
-- This is a function declaration.
doubleMe x = x + x
-- You can call a function like this; (ignore declaration)
-- Those are function calls or "Function application" in haskell.
-- (calling a function by putting a space after it and then typing out the parameters)
callSucc num = succ num
-- => callSucc 5
-- If a function takes two parameters you can also call it as an infix function;
callMax x y = x `max` y
-- => callMax 3 5
-- Not only can we call functions as infix with backticks,
-- we can also define them using backticks.
x `callMin` y = x `min` y
-- Examples.
-- Common Haskel (Or FP) Pattern.
-- Make basic functions that are obviously correct and
-- then combining them into more complex functions
doubleUs x y = doubleMe x + doubleMe y
-- => doubleUs 3 5
-- Functions in Haskell don't have to be in any particular order,
-- so it doesn't matter if you define doubleMe first and then doubleUs
-- or if you do it the other way around.
-- If inside function.
doubleIfSmallThan100 x = if x >= 100 then x else x * 2
-- In Haskell every expression and function must return something.
-- So you cant ommit else part. Else part is mandatory in Haskell.
-- Another thing about the if statement in Haskell is that it is an expression.
-- An expression is basically a piece of code that returns a value.
-- And therefore it can be used anywhere where a value is expected.
-- => 4 * (if 10 > 5 then 10 else 0) + 2
-- ' (apostrophe) is a valid character in functions (function names),
-- we can make a function like (doubleSmallNumber' ...).
-- We usually use ' to either denote a strict version of a function (one that isn't lazy)
-- or a slightly modified version of a function or a variable.
doubleIfSmallThan100' x = (if x >= 100 then x else x * 2) + 1
betterDoubleIfSmallThan100' x = succ (if x >= 100 then x else doubleMe x)
-- When a function doesn't take any parameters,
-- we usually say it's a definition (or a name).
conanO'Brien = "It's a-me, Conan O'Brien!"