Haskell 基础
What's Special With Haskell
Lazy V.S strict
Haskell is a lazy language, which means that no computation takes place unless it is forced to take place when the result of that computation is used.
Destructive update does not exist in Haskell. (e.g. int x = 5; x = x + 1不能运行,但能定义)
Pure Functional
Functions that do not have side effects are called pure(无副作用)
referential transparency : basically states that if two functions f and g produce the same values for the same arguments, then we may replace f with g
Details
-
case sensitive: 函数名小写开头,变量类型大写开头
-
parentheses: parentheses aren't required around function arguments
-
Composition: In mathematics we write $ f\circ g$ to mean "f following g," in Haskell we write
f . galso to mean "f following g." -
Infix(中缀)
- infix to non-infix: parentheses (+)
- non-infix to infix: backquote ``
内置类型
Tuple
tuples are allowed to be heterogeneous
fst and snd won't work on anything longer than a pair
List
lists must be homogeneous
length
head : returns the first element of a (non-empty) list
tail : returns all but the first element
use function on List: map, filter, foldr
foldr && foldl
folding is like replacing (:) with a particular function and ([]) with an initial element
foldr assumes the function is right-associative:
foldr (-) 1 [4,8,5]
==> 4 - (foldr (-) 1 [8,5])
==> 4 - (8 - foldr (-) 1 [5])
==> 4 - (8 - (5 - foldr (-) 1 []))
foldl uses the opposite bracketing
foldl (-) 1 [4,8,5]
==> foldl (-) (1 - 4) [8,5]
==> foldl (-) ((1 - 4) - 8) [5]
==> foldl (-) (((1 - 4) - 8) - 5) []
String
is simply a list of Chars
concatenated string with: ++
Compiling
- Must have function
maininmodule Main ghc --make Test.hs -o testghci Test.hs
Function
structure
if else
- you must have both a
**then**and an**else**clause - The indentation is important. Haskell uses a system called "layout" to structure its code like python

浙公网安备 33010602011771号