𝖄𝕺🌎𝕿𝕽𝕺¥

𝖄𝕺🌎𝕿𝕽𝕺¥

𝕴 𝖉𝖔 𝖒𝖆𝖌𝖎𝖈
github

Haskell笔记一 —— 入门 算数 运算符 未.定义变量 列表 字符.串 类型

添加模块#

ghci> :module + Data.Ratio

算数 + - * / ** ^ %#

基本的#

ghci> 7.0 / 2.0
3.5
ghci> 7 / 2
3.5

ghci> 2 + 2
4
ghci> (+) 2 2
4

** 和 ^#

- ** 可用于浮点数幂
ghci> 2.2**3.3
13.489468760533386
- ^ 只能用于整数幂
ghci> 2.2^3.3
<interactive> error:

%

分数的分子和分母必须都是整数类型

ghci>11 % 29
11 % 29
ghci>it :: Ratio Integer
11 % 29

ghci>3.14 % 8
<interactive>:7:1: error:

特殊运算 e.g. succ pred sqrt sin truncate round floor ceiling#

ghci>sqrt 16
4.0
ghci>succ 6
7
ghci>succ 7
8
ghci>pred 9
8
ghci>pred 8
7
ghci>sin (pi / 2)
1.0
ghci>truncate pi    --取舍
3
ghci>round 3.5    --四舍五入
4
ghci>round 3.4
3
ghci>floor 3.7
3
ghci>ceiling 3.3
4

运算符#

布尔逻辑 && ||#

ghci> True && False
False
ghci> False || True
True

0 不代表 False,非 0 不代表 True

值比较 == <>>= <= /= not#

ghci> 1 == 1
True
ghci> 2 < 3
True
ghci> 4 >= 3.99
True
ghci> 1 /= 1    -- 不等于
False
ghci> not True  --not用法
False

优先级 ()#

ghci> :info (+)     --查询+的优先级
class (Eq a, Show a) => Num a where
  (+) :: a -> a -> a
  ...
    -- Defined in GHC.Num
infixl 6 +      --优先级为6级

等级越高越优先

未定义的变量以及定义变量 e.g. pi , e#

ghci> pi
3.141592653589793

ghci> e
<interactive> Not in scope: `e'
e不存在,需自己定义
ghci> let e = exp 1
ghci> e
2.718281828459045

列表#

列表中元素必须同类型
列表可以是任意长度

[]
ghci> [3,1,3] ++ [3,7]
[3,1,3,3,7]
ghci> 1 : [2,3]
[1,2,3]
ghci> 1 : []
[1]

: 只可用于增加一个元素到列表的头部
可接空 []

字符串和字符 putStrLn ""#

ghci> "This is a string."
"This is a string."
ghci> putStrLn "Here's a newline -->\n<-- See?"
Here's a newline -->
<-- See?

文本字符串是单一字符的列表

ghci> let a = ['l', 'o', 't', 's', ' ', 'o', 'f', ' ', 'w', 'o', 'r', 'k']
ghci> a
"lots of work"
ghci> a == "lots of work"
True
ghci> "" == []
True
ghci> 'a':"bc"
"abc"
ghci> "foo" ++ "bar"
"foobar"

类型#

类型名字 都以大写字母开头
变量名字 都以小写字母开头

:set +t 显示类型功能。是 ghci 的辅助功能

:unset +t 关闭显示类型

:type检查类型

Prelude Data.Ratio> :type 'a'
'a' :: Char

Prelude Data.Ratio> "foo"
"foo"

Prelude Data.Ratio> :type it
it :: [Char]
Prelude> :set +t

Prelude> 'c'    -- 输入表达式
'c'             -- 输出值
it :: Char      -- 输出值的类型

Prelude> "foo"
"foo"
it :: [Char]

整数类型为 Integer 。 Integer 类型值的长度只受限于系统的内存大小。

加载中...
此文章数据所有权由区块链加密技术和智能合约保障仅归创作者所有。