Advertisement
trapsgay

haskell wiki temp

Mar 5th, 2021
1,329
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Haskell 14.33 KB | None | 0 0
  1. ---------------------------------------------------------------------------------
  2. -- This is structured to be split into the sections from the description
  3. -- but be able to compile as well
  4. ---------------------------------------------------------------------------------
  5.  
  6. {-
  7. NOTEs
  8. add something on arrays in Haskell
  9. -}
  10.  
  11. ---- Variables and Operations allowed by the language
  12.  
  13. -- Variables are declared by using the name = value (unless declared in a function)
  14. myName = "Aidan" -- String
  15. myAge = 18 -- Int
  16. myHeight = 1.7 -- Float
  17. isMale = True -- Bool
  18.  
  19. {-
  20.   To declare the type of the variable, before assignment, add name::type
  21.   This is called a type declaration signature.
  22. -}
  23. lastName::String
  24. lastName = "Pinard"
  25.  
  26. seventySevenPointNine::Float
  27. seventySevenPointNine = 77.9
  28.  
  29. {- Variables cannot be reassigned;
  30.      lastName = "Phillip" <<-- error: Multiple declarations of `lastName'
  31.    And they must begin with a lowercase letter.
  32.      Nineteen = 19 <<-- error: Not in scope: data constructor `Nineteen'
  33.  
  34.    After the first letter they can have numbers, letters,
  35.    underscores (_) and apostrophes ('). using an apostrophe is commonly
  36.    used to indicate a modified version of a value.
  37. -}
  38. x' = x + 2 -- x' (x prime, like in math) is 2 larger than x
  39. a_vAR1A8le_NAmE = "This works"
  40.  
  41. -- Math uses the normal operators
  42. x = 12 + 13 {- Note: x is declared here, is used before in x' = x + 2.
  43.                This is due to the fact that variables cannot change. -}
  44. y = (10 - 5) * 3
  45.  
  46. z::Float
  47. z = 13/4  {-
  48.   This is normal division and will return a float.
  49.   Adding z::Int before will cause an error.
  50.   The / operator returns a float value
  51.   (specifically a Fractional value, which is not exactly a float).
  52. -}
  53.  
  54. z'::Int
  55. z' = 13 `div` 4 -- This is integer division
  56.  
  57. -- Boolean operations
  58. notTrue = not True -- False
  59. notFalse = not False -- True
  60. probablyTrue = 1 <= 10 && ( 10 > 5 || 'a' /= 'a') && 3.5 == 3.5
  61. {-
  62. not -- inverts the Boolean
  63. <=, < -- less than or equal to, less than,
  64. >, >= -- greater than, greater than or equal to
  65. && -- Logical and
  66. || -- Logical or
  67. == -- equal to
  68. /= -- not equal to
  69. -}
  70.  
  71. -- Chars, Strings, Lists
  72. a = 'a' -- a Char or character
  73. abc = "abc" -- a String. Double quotes must be used for a string.
  74.  
  75. -- to 'add' two strings, use ++. The + operator only works on numbers
  76. abcdef = abc ++ "def"
  77.  
  78. -- Printing strings is done using putStr or putStrLn
  79. --putStr "Hello\n" -- putStr just prints the characters
  80. --putStrLn "Hello" -- putStrLn prints the characters and adds a newline
  81. -- NOTE this must be done within an IO function (see: functions)
  82.  
  83. -- Getting input is done using getline
  84.  
  85.  
  86. abcList = ['a', 'b', 'c'] {- A list (formally a linked list).
  87.   All values in a list must have the same type.
  88.   Values are separated by commas.
  89.   -}
  90.  
  91. {- Note: A string is a list of characters in Haskell -}
  92. stringAndCharList = abc == abcList -- True
  93. anotherName::[Char] -- the [] represent a List.
  94. anotherName = "Joseph" -- This compiles
  95. -- the ++ operator concatenates lists (hence it concatenates strings as well)
  96. oneToSix = [1,2] ++ [3,4,5,6]
  97.  
  98. {- Lists can be indexed like an array using the !! operator. Note, when accessing
  99.    a value in a list, the program will iterate through each value before the value
  100.    you are trying to access.
  101.  
  102.    Lists in Haskell are zero indexed (Like C++ and Java)
  103.    -}
  104. c = abcList !! 2 -- 'c'
  105. -- As strings are just Char Arrays, they can be indexed as well
  106. d = abcdef !! 3 -- 'd'
  107.  
  108. -- List functions
  109. one = head oneToSix -- 1. head gives the first value in a list
  110. twoToSix = tail oneToSix -- [2,3,4,5,6]. tail returns every value but the first
  111. six = last oneToSix -- 6. last gives the last value in the list.
  112. -- Note: as lists are iterated through to get a value, the time for head and tail are constant
  113. -- but the time for last is dependent on the length of the list.
  114. zeroToSix = 0:oneToSix -- [0,1,2,3,4,5,6] : adds a value to the front of the list
  115. oneToTen = [1..10] -- [x..y] creates a list from x to y in increments of 1 given that x < y
  116. -- emptyList = [10..1]
  117. -- [] an empty list is returned as Haskell uses positive increments
  118. -- Haskell gives a warning when it detects an empty List
  119.  
  120. evenNumbersUpToTen = [0,2..10] {- [x,y..z] creates a list from x to z.
  121.   y is the second value and y - x is the incrementing value.
  122.   -}
  123. tenToOne = [10,9..1] -- Using the increment, decreasing lists can be made
  124.  
  125. -- Generated lists can be of non-numeric values as well
  126. aToZ = ['a'..'z']
  127.  
  128. {- Haskell also allows for infinite lists. Haskell does not create a variable in
  129.    memory immediately but whenever the value is needed it generates the required
  130.    value. This is called Lazy evaluation. Haskell also has Datatypes which are
  131.    very similar to mathematical concepts and can handle extremely large computations.
  132.    The Integer datatype is one such example. (NOTE: this is not Int. Int is similar to
  133.    int in C++, while Integer is a Haskell expression of the mathematical concept of an
  134.    integer.)
  135.    -}
  136.  
  137. oneToInfinity = [1..]
  138.  
  139. -- List comprehension
  140. -- List comprehension is a method of creating lists and modifying them immediately
  141. squaresToFive = [x*x | x <- [1..5]] {- For the values 1 to 5 ([1..5]),
  142.   save each in x, (x <- ) and apply the operation x*x.
  143.   [operation | temporary_variable <- [list to operate on]]
  144.  
  145.   a similar c++ equivalent
  146.   int x[5] = {1,2,3,4,5};
  147.   for( int i = 0; i < 5; i++) {
  148.     x[i] = x[i]*x[i];
  149.   }
  150.   // for each value in the array, square it.
  151. -}
  152.  
  153. squaresLessThanTen = [x*x | x <- [1..5], x*x < 10]{- Same as above, except only add
  154.   the squares which are less than 10.
  155.   [operation | temporary_variable <- [list to operate on], condition]
  156.   -}
  157.  
  158. -- Tuples
  159. -- Tuples are a way of quickly grouping together 2 values that may be related
  160. parse17 = (True, 17) {- A function which parses a string as an integer may return
  161.   a tuple with a Bool indicating whether the parse failed and an Int for a successful
  162.   parse.
  163.   -}
  164.  
  165. thingsIKnow = ("math", 13, ['h', 'o', 'u', 's', 'e'], 55.676, ("car", "house"))
  166. -- Tuples can be of any length, and hold any other datatype, including other tuples.
  167.  
  168. -- Tuples with 2 values (pair) are most commonly used, and have functions which
  169. -- return values in them
  170. parseSucceeded = fst parse17 -- Gets the first value in a pair
  171. parseValue = snd parse17 -- Gets the second value in a pair
  172. -- These functions only work on pairs
  173. -- fst ("house", "car", 2323) -- gives an error
  174.  
  175. -- Tuples can also be "decomposed" immediately upon access, instead of using fst and snd
  176. -- This can work with tuples of any size
  177. (parseSucceeded', parseValue') = parse17 -- Splits parse17 into two variables
  178. -- A _ can be used to ignore values
  179. (_,_,_,number,_) = thingsIKnow
  180. {- ignores the first, second, third and fifth values and assigns the
  181.    fourth to number
  182.    -}
  183.  
  184.  
  185.  
  186. ---- Decision and Conditional Statements
  187.  
  188. -- If statements
  189. hello = if myAge < 18 then "hello small child" else "Hello Adult Person"
  190. {- The if then else function requires options for all cases.
  191.    As variables cannot be changed, the value of an If then else is
  192.    usually directly assigned to a variable. Haskell does not allow for
  193.    accidental nonexistent values (like some functions returning null
  194.    in C style languages), so each value must exist. For situations where
  195.    a value may or may not exist, Haskell provides the Maybe type.
  196.    -}
  197.  
  198.  
  199. -- Conditionals can also be done on function parameters (see Functions).
  200.  
  201.  
  202.  
  203. ---- Loops
  204. {- Since Haskell is a functional language and variables cannot be reassigned,
  205.    if statements are slightly different and normal for/while/dowhile loops do
  206.    not exist, as those constructs are meant for imperative languages. Looping
  207.    is done using recursion. (See Functions)
  208.  
  209.    Looping over a list or similar can be done using the map function
  210.    -}
  211.  
  212. rootsTo100 = map sqrt [1..100] -- apply the function sqrt to each value in the list [1..100]
  213. -- rootsTo100 is now [1, 1.4142, ...., 10]
  214.  
  215.  
  216.  
  217. ---- Functions
  218.  
  219. {- Functions in Haskell can get very complicated for persons new to functional
  220.    programming, but at a basic level, it is just like math.
  221.    -}
  222. -- Functions are declared just like variables, with parameters between the name
  223. -- and the = . Functions parameters in Haskell are simply separated by spaces
  224. add a b = a + b -- Takes parameters a and b and returns the last operation
  225.  
  226.  
  227. sevenTeen = add 10 7 -- 10 + 7 = seventeen
  228.  
  229. -- Functions also have type signatures, and they define the return type and
  230. -- the types of the parameters
  231. addThreeInts::Int -> Int -> Int -> Int
  232. -- The last value is the return value, and the other values show the parameters
  233. -- the -> shows how the values are separated (They have a specific meaning which comes
  234. -- from how Haskell works with functions (see partial application))
  235. addThreeInts a b c = a + b + c
  236. fifty = addThreeInts 15 18 22 -- Adds the three integers
  237.  
  238. -- Functions with multiple lines
  239. aToBList a b =
  240.   if a < b then
  241.     [a..b]
  242.   else
  243.     [b..a]
  244.  
  245. -- Functions which execute differently depending on their
  246. -- parameters can be expressed using guards
  247. aToBList' a b
  248.        | a < b = [a..b] -- if a less than b make a list from a to b
  249.        | b < a = [b..a] -- else make a list from b to a
  250.        | otherwise = []
  251.        -- if they cannot be compared then return an empty list.
  252.        -- otherwise is
  253.  
  254. -- You can also make infix functions/operators (like for math etc)
  255.  
  256. -- A custom math operator to quickly get the hypotenuse from two sides
  257. (<!>) a b = sqrt $ a^2 + b^2
  258. five = 3 <!> 4 -- Note, brackets are not used when calling the function
  259. thirteen = (<!>) 5 12 -- they can also be called like normal functions with brackets
  260.  
  261. -- or to do integer division more easily
  262. (//) a b = a `div` b
  263. twelve = 150 // 12
  264.  
  265. -- normal functions with two parameters can also be called as infix operators
  266. -- using backticks
  267. fourteen = 12 `add` 2
  268.  
  269. -- tuple pattern matching can also be done with functions to extract values
  270. sumOfQuintuple (a,b,c,d,e) = a + b + c + d + e
  271. -- as well as to ignore values
  272. -- fst and snd are defined as
  273. fst' (x, _) = x
  274. snd' (_,  y) = y
  275.  
  276. -- Functions in Haskell return the last value/line in the function
  277. -- Sometimes, longer functions may be more difficult to understand what
  278. -- it returns, so they can be expressed using the where clause
  279. roots (a,b,c) = (x1, x2) where
  280.   x1 = e + sqrt d / (2 * a)
  281.   x2 = e - sqrt d / (2 * a)
  282.   d = b * b - 4 * a * c  
  283.   e = - b / (2 * a)  
  284. -- We define a function called roots, which takes a tuple of 3 values
  285. -- representing a polynomial (ax^2 + bx + c) and returns the roots of
  286. -- the function as a tuple (x1, x2). Here we state the return value first
  287. -- then define what each value represents. Remember, variables in Haskell
  288. -- can be defined before use, as they are static values (i.e. they will
  289. -- always be the same, so they can be replaced by their values).
  290. -- Note this is similar to mathematical equations, where you state the
  291. -- equation, then state what each value represents
  292. -- (Area of a square = x^2 *where* x is the length of one side)
  293.  
  294.  
  295.  
  296. ----------------------------------------------------------
  297. -- ADD SOMETHING FOR RECURSION
  298. ----------------------------------------------------------
  299.  
  300.  
  301.  
  302. (%) = mod
  303.  
  304.  
  305.  
  306. -- Partial application
  307. -- Partial application is a large part of functional programming
  308. -- In imperative languages like c++, all the parameters to a function
  309. -- must be provided anywhere the function is used
  310. -- In Haskell, if you do not provide all the arguments to a function,
  311. -- it simply returns a function which takes the remaining arguments
  312. -- as parameters. For example:
  313. add1 = add 1 -- Partially applies the add function from before
  314. -- Then you can use add1 x in the same way as add 1 x
  315. fourtyFive = add1 44
  316. fourtyFive' = add 1 44
  317. -- These two functions are equivalent
  318.  
  319. -- The -> in the type declaration for a function represents the partial
  320. -- application. E.g. Int -> Int -> Float is a function that takes int,
  321. -- then returns [a function that then takes int and returns float.]
  322.  
  323. -- Partial application is used in situations where a certain
  324. -- function is repeatedly given the same argument, so it is abridged to
  325. -- a shorter function call
  326. aVeryLongVariableNameForAList = [1..100]
  327. getPosition list index = list !! index
  328. indexLongList = getPosition aVeryLongVariableNameForAList
  329. -- Now indexLongList can be used instead of getPosition aVeryLongVariableNameForAList.
  330.  
  331. -- There are also functions which can accept functions as parameters
  332. -- For example, the map function accepts a function and a list or array
  333. -- and applies the function to each value in the list, and returns a new
  334. -- list of the new values
  335. twoToEleven = map add1 [1..10] -- applies add1 to each value in the list
  336. -- and returns the new values as a list
  337.  
  338. -- Sometimes, you may want to apply a onetime function to a list so
  339. -- you can use an anonymous function, also called a lambda function
  340. -- with the map.
  341. oneToHundred = map (\ x -> x*2) [1..10]
  342. -- lambda functions are declared as
  343. -- (\ parameters -> processing and return value)
  344.  
  345. helloWorld = (\ a b c -> a++b++c) ("Hello") (" ") ("World!")
  346. -- a function that concatenates the three strings to form the full string
  347.  
  348.  
  349. ----------------
  350. -- IO Functions
  351. ----------------
  352. -- Functions that use any form of IO in Haskell are different to normal
  353. -- functions. These have side effects (i.e. their output can depend on
  354. -- things other than just their input). A function has no side effects
  355. -- if for a given input value, the function will always output the exact
  356. -- same thing. If a function depends on IO, (i.e. reading input from a
  357. -- console, or writing to a file[which may or may not fail], etc.) it's
  358. -- output and the way it processes information can differ. Unlike normal
  359. -- variables, which are static values for their lifetime, IO variables
  360. -- are actually functions from which a value can be extracted and stored
  361. -- as a normal variable.
  362.  
  363. -- ------ ------ -- -- - --- ----- --
  364. -- ADD THE EXAMPLE FROM MONADIC BIND MEDIUM ARTICLE
  365.  
  366. {--
  367. arq a b =
  368.   if myAge < 10 then
  369.     5
  370.   else
  371.     6
  372.   a + b
  373.  
  374.  
  375. --}
  376.  
  377. sumto10 = foldl (+) 0 [1..10]
  378.  
  379.  
  380. -- The main function
  381. main = do
  382.   putStrLn myName
  383.   putStrLn aToZ
  384.   putStrLn "Enter something to say: "
  385.   x <- getLine
  386.   putStrLn x
  387.   putStrLn $ aToBList 'a' 'r'
  388.   putStrLn $ aToBList 'a' 'q'
  389.   print sumto10
  390.   putStrLn $ show $ 12 <!> 15
  391.   putStrLn $ addWords "Hello"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement