一直挺想看看Haskell的函数式编程是怎么样的,所以开始学,但是最近实习+毕设可能稍微忙一些,而且发现自己之前的记录方式太繁复了,可能会把那个网页的大半都拷下来,思考要不要做这么笨B的事了。
Introduction
What’s Haskell
- Haskell is a purely functional programming language.
- In purely functional languages, a function has no side-effects.
- The only thing a function can do is calculate something and return it as a result.
- referential transparency: If a function is called twice with the same parameters, it’s guaranteed to return the same result.
- lazy language: Haskell won’t execute functions and calculate things until it’s really forced to show you a result.
- statically typed and has type inference
Install Haskell compiler
- download at Haskell Platform
- for ubuntu: (don’t know why it is 630MB large …)
1
sudo apt-get install haskell-platform
Starting Out
Ready, set, go!
- run
ghci
- use
:set prompt "ghci> "
to change prompt- but what does this prompt use for?
1 | sparta:~$ ghci |
+
works only on things that are considered numbers.==
works on any two things that can be compared.- prefix | infix
1
div 92 10 is equal to 92 `div` 10
Baby’s first functions
it doesn’t matter if a function is define later then be used. (compile successfully)
if statements: else part is mandatory in Haskell
An expression is basically a piece of code that returns a value.
symbol ‘ can be use in function name, for example
foo'
is a different function withfoo
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.
comment:
--
functions can’t begin with uppercase letters
definition(or name): a function which doesn’t take any parameters
An intro to lists
- lists are a homogenous data structure – can’t mix type
let
keyword can define a name – otherwise a parse error will be triggered
1 | ghci> let lostNumbers = [4,8,15,16,23,42] |
strings are lists, for example
"hello"
is just syntactic sugar for['h', 'e', 'l', 'l', 'o']
++
operator can put two lists together (two lists)- Haskell has to walk through the whole list on the left side of
++
, terrible when list is too long
- Haskell has to walk through the whole list on the left side of
1 | ghci> [1,2,3,4] ++ [9,10,11,12] |
:
operator can put element at the beginning of a list (a elem and a list)
1 | ghci> 'A':" SMALL CAT" |
[1,2,3]
is actually just syntactic sugar for1:2:3:[]
!!
operator: get an elementout of a list by index. The indices start at 0.
1 | ghci> "Steve Buscemi" !! 6 |
- Lists can also contain lists.
1 | ghci> let b = [[1,2,3,4],[5,3,3,3],[1,2,2,3,4],[1,2,3]] |
- list comparasion: in Lexicographical order. First the heads are compared. If they are equal then the second elements are compared, etc.
1 | ghci> [3,2,1] > [2,1,0] |
head
takes a list and returns its head. The head of a list is basically its first element.tail
takes a list and returns its tail. In other words, it chops off a list’s head.last
takes a list and returns its last element.init
takes a list and returns everything except its last element.