𝖄𝕺🌎𝕿𝕽𝕺¥

𝖄𝕺🌎𝕿𝕽𝕺¥

𝕴 𝖉𝖔 𝖒𝖆𝖌𝖎𝖈
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 類型值的長度只受限於系統的內存大小。

載入中......
此文章數據所有權由區塊鏈加密技術和智能合約保障僅歸創作者所有。