Advertisement
Guest User

Untitled

a guest
Aug 19th, 2017
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Haskell 11.98 KB | None | 0 0
  1. -- Single line comments start with two dashes.
  2. {- Multiline comments can be enclosed
  3. in a block like this.
  4. -}
  5.  
  6. ----------------------------------------------------
  7. -- 1. Primitive Datatypes and Operators
  8. ----------------------------------------------------
  9.  
  10. -- You have numbers
  11. 3 -- 3
  12.  
  13. -- Math is what you would expect
  14. 1 + 1 -- 2
  15. 8 - 1 -- 7
  16. 10 * 2 -- 20
  17. 35 / 5 -- 7.0
  18.  
  19. -- Division is not integer division by default
  20. 35 / 4 -- 8.75
  21.  
  22. -- integer division
  23. 35 `div` 4 -- 8
  24.  
  25. -- Boolean values are primitives
  26. True
  27. False
  28.  
  29. -- Boolean operations
  30. not True -- False
  31. not False -- True
  32. 1 == 1 -- True
  33. 1 /= 1 -- False
  34. 1 < 10 -- True
  35.  
  36. -- In the above examples, `not` is a function that takes one value.
  37. -- Haskell doesn't need parentheses for function calls...all the arguments
  38. -- are just listed after the function. So the general pattern is:
  39. -- func arg1 arg2 arg3...
  40. -- See the section on functions for information on how to write your own.
  41.  
  42. -- Strings and characters
  43. "This is a string."
  44. 'a' -- character
  45. 'You cant use single quotes for strings.' -- error!
  46.  
  47. -- Strings can be concatenated
  48. "Hello " ++ "world!" -- "Hello world!"
  49.  
  50. -- A string is a list of characters
  51. ['H', 'e', 'l', 'l', 'o'] -- "Hello"
  52. "This is a string" !! 0 -- 'T'
  53.  
  54.  
  55. ----------------------------------------------------
  56. -- 2. Lists and Tuples
  57. ----------------------------------------------------
  58.  
  59. -- Every element in a list must have the same type.
  60. -- These two lists are equal:
  61. [1, 2, 3, 4, 5]
  62. [1..5]
  63.  
  64. -- Ranges are versatile.
  65. ['A'..'F'] -- "ABCDEF"
  66.  
  67. -- You can create a step in a range.
  68. [0,2..10] -- [0, 2, 4, 6, 8, 10]
  69. [5..1] -- [] (Haskell defaults to incrementing)
  70. [5,4..1] -- [5, 4, 3, 2, 1]
  71.  
  72. -- indexing into a list
  73. [1..10] !! 3 -- 4 (zero-based indexing)
  74.  
  75. -- You can also have infinite lists in Haskell!
  76. [1..] -- a list of all the natural numbers
  77.  
  78. -- Infinite lists work because Haskell has "lazy evaluation". This means
  79. -- that Haskell only evaluates things when it needs to. So you can ask for
  80. -- the 1000th element of your list and Haskell will give it to you:
  81.  
  82. [1..] !! 999 -- 1000
  83.  
  84. -- And now Haskell has evaluated elements 1 - 1000 of this list...but the
  85. -- rest of the elements of this "infinite" list don't exist yet! Haskell won't
  86. -- actually evaluate them until it needs to.
  87.  
  88. -- joining two lists
  89. [1..5] ++ [6..10]
  90.  
  91. -- adding to the head of a list
  92. 0:[1..5] -- [0, 1, 2, 3, 4, 5]
  93.  
  94. -- more list operations
  95. head [1..5] -- 1
  96. tail [1..5] -- [2, 3, 4, 5]
  97. init [1..5] -- [1, 2, 3, 4]
  98. last [1..5] -- 5
  99.  
  100. -- list comprehensions
  101. [x*2 | x <- [1..5]] -- [2, 4, 6, 8, 10]
  102.  
  103. -- with a conditional
  104. [x*2 | x <- [1..5], x*2 > 4] -- [6, 8, 10]
  105.  
  106. -- Every element in a tuple can be a different type, but a tuple has a
  107. -- fixed length.
  108. -- A tuple:
  109. ("haskell", 1)
  110.  
  111. -- accessing elements of a pair (i.e. a tuple of length 2)
  112. fst ("haskell", 1) -- "haskell"
  113. snd ("haskell", 1) -- 1
  114.  
  115. ----------------------------------------------------
  116. -- 3. Functions
  117. ----------------------------------------------------
  118. -- A simple function that takes two variables
  119. add a b = a + b
  120.  
  121. -- Note that if you are using ghci (the Haskell interpreter)
  122. -- You'll need to use `let`, i.e.
  123. -- let add a b = a + b
  124.  
  125. -- Using the function
  126. add 1 2 -- 3
  127.  
  128. -- You can also put the function name between the two arguments
  129. -- with backticks:
  130. 1 `add` 2 -- 3
  131.  
  132. -- You can also define functions that have no letters! This lets
  133. -- you define your own operators! Here's an operator that does
  134. -- integer division
  135. (//) a b = a `div` b
  136. 35 // 4 -- 8
  137.  
  138. -- Guards: an easy way to do branching in functions
  139. fib x
  140.   | x < 2 = 1
  141.   | otherwise = fib (x - 1) + fib (x - 2)
  142.  
  143. -- Pattern matching is similar. Here we have given three different
  144. -- equations that define fib. Haskell will automatically use the first
  145. -- equation whose left hand side pattern matches the value.
  146. fib 1 = 1
  147. fib 2 = 2
  148. fib x = fib (x - 1) + fib (x - 2)
  149.  
  150. -- Pattern matching on tuples:
  151. foo (x, y) = (x + 1, y + 2)
  152.  
  153. -- Pattern matching on lists. Here `x` is the first element
  154. -- in the list, and `xs` is the rest of the list. We can write
  155. -- our own map function:
  156. myMap func [] = []
  157. myMap func (x:xs) = func x:(myMap func xs)
  158.  
  159. -- Anonymous functions are created with a backslash followed by
  160. -- all the arguments.
  161. myMap (\x -> x + 2) [1..5] -- [3, 4, 5, 6, 7]
  162.  
  163. -- using fold (called `inject` in some languages) with an anonymous
  164. -- function. foldl1 means fold left, and use the first value in the
  165. -- list as the initial value for the accumulator.
  166. foldl1 (\acc x -> acc + x) [1..5] -- 15
  167.  
  168. ----------------------------------------------------
  169. -- 4. More functions
  170. ----------------------------------------------------
  171.  
  172. -- partial application: if you don't pass in all the arguments to a function,
  173. -- it gets "partially applied". That means it returns a function that takes the
  174. -- rest of the arguments.
  175.  
  176. add a b = a + b
  177. foo = add 10 -- foo is now a function that takes a number and adds 10 to it
  178. foo 5 -- 15
  179.  
  180. -- Another way to write the same thing
  181. foo = (10+)
  182. foo 5 -- 15
  183.  
  184. -- function composition
  185. -- the operator `.` chains functions together.
  186. -- For example, here foo is a function that takes a value. It adds 10 to it,
  187. -- multiplies the result of that by 4, and then returns the final value.
  188. foo = (4*) . (10+)
  189.  
  190. -- 4*(10+5) = 60
  191. foo 5 -- 60
  192.  
  193. -- fixing precedence
  194. -- Haskell has an operator called `$`. This operator applies a function
  195. -- to a given parameter. In contrast to standard function application, which
  196. -- has highest possible priority of 10 and is left-associative, the `$` operator
  197. -- has priority of 0 and is right-associative. Such a low priority means that
  198. -- the expression on its right is applied as the parameter to the function on its left.
  199.  
  200. -- before
  201. even (fib 7) -- false
  202.  
  203. -- equivalently
  204. even $ fib 7 -- false
  205.  
  206. -- composing functions
  207. even . fib $ 7 -- false
  208.  
  209.  
  210. ----------------------------------------------------
  211. -- 5. Type signatures
  212. ----------------------------------------------------
  213.  
  214. -- Haskell has a very strong type system, and every valid expression has a type.
  215.  
  216. -- Some basic types:
  217. 5 :: Integer
  218. "hello" :: String
  219. True :: Bool
  220.  
  221. -- Functions have types too.
  222. -- `not` takes a boolean and returns a boolean:
  223. -- not :: Bool -> Bool
  224.  
  225. -- Here's a function that takes two arguments:
  226. -- add :: Integer -> Integer -> Integer
  227.  
  228. -- When you define a value, it's good practice to write its type above it:
  229. double :: Integer -> Integer
  230. double x = x * 2
  231.  
  232. ----------------------------------------------------
  233. -- 6. Control Flow and If Expressions
  234. ----------------------------------------------------
  235.  
  236. -- if-expressions
  237. haskell = if 1 == 1 then "awesome" else "awful" -- haskell = "awesome"
  238.  
  239. -- if-expressions can be on multiple lines too, indentation is important
  240. haskell = if 1 == 1
  241.             then "awesome"
  242.             else "awful"
  243.  
  244. -- case expressions: Here's how you could parse command line arguments
  245. case args of
  246.   "help" -> printHelp
  247.   "start" -> startProgram
  248.   _ -> putStrLn "bad args"
  249.  
  250. -- Haskell doesn't have loops; it uses recursion instead.
  251. -- map applies a function over every element in a list
  252.  
  253. map (*2) [1..5] -- [2, 4, 6, 8, 10]
  254.  
  255. -- you can make a for function using map
  256. for array func = map func array
  257.  
  258. -- and then use it
  259. for [0..5] $ \i -> show i
  260.  
  261. -- we could've written that like this too:
  262. for [0..5] show
  263.  
  264. -- You can use foldl or foldr to reduce a list
  265. -- foldl <fn> <initial value> <list>
  266. foldl (\x y -> 2*x + y) 4 [1,2,3] -- 43
  267.  
  268. -- This is the same as
  269. (2 * (2 * (2 * 4 + 1) + 2) + 3)
  270.  
  271. -- foldl is left-handed, foldr is right-handed
  272. foldr (\x y -> 2*x + y) 4 [1,2,3] -- 16
  273.  
  274. -- This is now the same as
  275. (2 * 1 + (2 * 2 + (2 * 3 + 4)))
  276.  
  277. ----------------------------------------------------
  278. -- 7. Data Types
  279. ----------------------------------------------------
  280.  
  281. -- Here's how you make your own data type in Haskell
  282.  
  283. data Color = Red | Blue | Green
  284.  
  285. -- Now you can use it in a function:
  286.  
  287. say :: Color -> String
  288. say Red   = "You are Red!"
  289. say Blue  = "You are Blue!"
  290. say Green = "You are Green!"
  291.  
  292. -- Your data types can have parameters too:
  293.  
  294. data Maybe a = Nothing | Just a
  295.  
  296. -- These are all of type Maybe
  297. Just "hello"    -- of type `Maybe String`
  298. Just 1          -- of type `Maybe Int`
  299. Nothing         -- of type `Maybe a` for any `a`
  300.  
  301. ----------------------------------------------------
  302. -- 8. Haskell IO
  303. ----------------------------------------------------
  304.  
  305. -- While IO can't be explained fully without explaining monads,
  306. -- it is not hard to explain enough to get going.
  307.  
  308. -- When a Haskell program is executed, `main` is
  309. -- called. It must return a value of type `IO a` for some type `a`. For example:
  310.  
  311. main :: IO ()
  312. main = putStrLn $ "Hello, sky! " ++ (say Blue)
  313. -- putStrLn has type String -> IO ()
  314.  
  315. -- It is easiest to do IO if you can implement your program as
  316. -- a function from String to String. The function
  317. --    interact :: (String -> String) -> IO ()
  318. -- inputs some text, runs a function on it, and prints out the
  319. -- output.
  320.  
  321. countLines :: String -> String
  322. countLines = show . length . lines
  323.  
  324. main' = interact countLines
  325.  
  326. -- You can think of a value of type `IO ()` as representing a
  327. -- sequence of actions for the computer to do, much like a
  328. -- computer program written in an imperative language. We can use
  329. -- the `do` notation to chain actions together. For example:
  330.  
  331. sayHello :: IO ()
  332. sayHello = do
  333.   putStrLn "What is your name?"
  334.   name <- getLine -- this gets a line and gives it the name "name"
  335.   putStrLn $ "Hello, " ++ name
  336.  
  337. -- Exercise: write your own version of `interact` that only reads
  338. --           one line of input.
  339.  
  340. -- The code in `sayHello` will never be executed, however. The only
  341. -- action that ever gets executed is the value of `main`.
  342. -- To run `sayHello` comment out the above definition of `main`
  343. -- and replace it with:
  344. --   main = sayHello
  345.  
  346. -- Let's understand better how the function `getLine` we just
  347. -- used works. Its type is:
  348. --    getLine :: IO String
  349. -- You can think of a value of type `IO a` as representing a
  350. -- computer program that will generate a value of type `a`
  351. -- when executed (in addition to anything else it does). We can
  352. -- name and reuse this value using `<-`. We can also
  353. -- make our own action of type `IO String`:
  354.  
  355. action :: IO String
  356. action = do
  357.    putStrLn "This is a line. Duh"
  358.    input1 <- getLine
  359.    input2 <- getLine
  360.    -- The type of the `do` statement is that of its last line.
  361.    -- `return` is not a keyword, but merely a function
  362.    return (input1 ++ "\n" ++ input2) -- return :: String -> IO String
  363.  
  364. -- We can use this just like we used `getLine`:
  365.  
  366. main'' = do
  367.     putStrLn "I will echo two lines!"
  368.     result <- action
  369.     putStrLn result
  370.     putStrLn "This was all, folks!"
  371.  
  372. -- The type `IO` is an example of a "monad". The way Haskell uses a monad to
  373. -- do IO allows it to be a purely functional language. Any function that
  374. -- interacts with the outside world (i.e. does IO) gets marked as `IO` in its
  375. -- type signature. This lets us reason about which functions are "pure" (don't
  376. -- interact with the outside world or modify state) and which functions aren't.
  377.  
  378. -- This is a powerful feature, because it's easy to run pure functions
  379. -- concurrently; so, concurrency in Haskell is very easy.
  380.  
  381.  
  382. ----------------------------------------------------
  383. -- 9. The Haskell REPL
  384. ----------------------------------------------------
  385.  
  386. -- Start the repl by typing `ghci`.
  387. -- Now you can type in Haskell code. Any new values
  388. -- need to be created with `let`:
  389.  
  390. let foo = 5
  391.  
  392. -- You can see the type of any value or expression with `:t`:
  393.  
  394. > :t foo
  395. foo :: Integer
  396.  
  397. -- Operators, such as `+`, `:` and `$`, are functions.
  398. -- Their type can be inspected by putting the operator in parentheses:
  399.  
  400. > :t (:)
  401. (:) :: a -> [a] -> [a]
  402.  
  403. -- You can get additional information on any `name` using `:i`:
  404.  
  405. > :i (+)
  406. class Num a where
  407.   (+) :: a -> a -> a
  408.   ...
  409.     -- Defined in ‘GHC.Num’
  410. infixl 6 +
  411.  
  412. -- You can also run any action of type `IO ()`
  413.  
  414. > sayHello
  415. What is your name?
  416. Friend!
  417. Hello, Friend!
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement