Haskell学习笔记:函数定义与local definition
程序员文章站
2024-01-29 19:32:34
...
Haskell学习笔记:函数定义与local definition
函数定义
-- guarded clauses
isEven :: Intergr -> Bool
isEven n
| n `mod` 2 == 0 = True
| otherwise = False
-- if-then-else
isEven2 :: Integer -> Bool
isEven2 n =
if n `mod` 2 == 0
then True
else False
- 函数isEven与isEven2表达意思相同
- First comes the type declaration then the function definition,其中:
1.Type declarations are optional
2.Haskell has type inference - Function clauses of the form ‘guard = expression’
Right-hand side applies if guard on left-hand side is satisfied - composition of functions via
isOdd :: Integer -> Bool
isOdd = not . isEven
- 函数变量命名以小写字母开头
- function application is left associative
局部定义函数1(let)
- 语法:let locals in,如下:
isEven3 :: Integer -> Bool
isEven3 n = let m = n `mod` 2
p = m == 0
in if p then True
else False
- isEven3 更精确地变量说明如下:
isEven3a :: Integer -> Bool
isEven3a n = let m :: Integer
m = n `mod` 2
p :: Bool
p = m == 0
in if p then True
else False
- 对于局部定义函数其传统:总是给出顶层函数类型,省略局部定义类型说明
局部定义函数2(where)
- 用where结构表达函数isEven3,如下:
isEven4 :: Integer -> Bool
isEven4 n = if p then True
else False
where
m = n `mod` 2
p = m == 0
总结
回味两个点:
guarded clauses 与 if-then-else语法区别与相同点
let 与 where的区别:前者let先给出判断条件,再in给出执行语句;后者先给出执行语句,再where带出判断条件