[Learning You a Haskell for Great Goods!] chapter 01 starting out

本文介绍了如何在CentOS/Fedora下安装Haskell,并通过多个示例演示了基本操作,包括布尔运算、数值运算、列表操作及函数定义等,适合Haskell初学者。

Installation

under CentOS/Fedora

# yum install ghc

 

Version

[root@bogon1 haskell]# ghc -v

Glasgow Haskell Compiler, Version 7.0.4, for Haskell 98, stage 2 booted by GHC version 7.0.4

 

Change prompt

echo :set prompt "ghci> " > ~/.ghci

 

Command

# Boolean

ghci> True && False

False

 

# call function, get successor of 8

ghci> succ 8

9

 

# load scripts

## echo doubleMe x = x + x > baby.hs

 

ghci> :l baby.hs

[1 of 1] Compiling Main             ( baby.hs, interpreted )

Ok, modules loaded: Main.

 

ghci> doubleMe 9

18

 

# Concatenation between list and string

ghci> [1,2,3,4] ++ [9,10,11,12]

[1,2,3,4,9,10,11,12]

 

or

 

ghci > 'A': "Small cat"

"A Small cat"

 

or

 

ghci> 5:[1,2]

[5,1,2]

 

# List operation

 

## get the element that's index = 3

ghci> "123456" !! 3

'4'

 

## comparing

ghci> [3,2,1] > [2,1,0]
True

## head vs tail, init vs last

ghci> head [5,4,3,2,1]
5

ghci> tail [5,4,3,2,1]
[4,3,2,1]

ghci> last [5,4,3,2,1]
1

ghci> init [5,4,3,2,1]
[5,4,3,2]

## length

ghci> length [5,4,3,2,1]
5

## is null or not

ghci> null [1,2,3]
False
ghci> null []
True

## reverse list

ghci> reverse [5,4,3,2,1]
[1,2,3,4,5]

## take the first N elements

ghci> take 3 [5,4,3,2,1]
[5,4,3]
ghci> take 1 [3,9,3]
[3]
ghci> take 5 [1,2]
[1,2]
ghci> take 0 [6,6,6]
[]

## drop the first N elements

ghci> drop 3 [8,4,2,1,5,6]
[1,5,6]
ghci> drop 0 [1,2,3,4]
[1,2,3,4]
ghci> drop 100 [1,2,3,4]
[]

## element in list or not

ghci> 4 `elem` [1 ,4 ]
True

or

ghci> elem 4 [1 , 4]
True

## range

ghci> [1..4]
[1,2,3,4]

 

## replicate

 

ghci> replicate 3 10

[10,10,10]

 

## List Comprehension

 

ghci> [x * 2 | x <- [1..10] ]

[2,4,6,8,10,12,14,16,18,20]

 

ghci> [x*2 | x <- [1..10], x *2 >= 12]

[12,14,16,18,20]

 

## differnces between list and tuple

list must be the same type of element

tuple could be different but if list contains at least one tuple, the number of element in tuple must be fixed

 

## pair

## contains only two element

## the following function work in pair only

 

## take the first element

ghci> fst (1,2)

1

 

## take the second element

ghci> snd (1,2)

2

 

# zip

# combine two list into one

ghci> zip [1,2] ["one","two"]

[(1,"one"),(2,"two")]

 

# commond pattern in functional programming

start with a certain set fo candidate solutions ,and apply transformations and filters to them util narrowed the possibilities down to the one solution

 

Note

doubleSmallNumber' is valid as a method name

转载于:https://www.cnblogs.com/abramsz/p/3989631.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值