haskell示例

1 排版规则

反引号能够将一个命令的标准输出插在一个命令行中任何位置

A `plus` asd

Unix 使用/ 左斜杠 windows使用\斜杠

和等号对齐非常重要;

以下是错误例子 未对齐;

常用关键字

导入模块

:module +Data.List

import Data.Char (digitToInt)

:module +Data.Char

:unset +m 取消输入多行;

:t add 可以得到函数类型

:set +m 可以输入多行;

Cmd 命令行下 runghc file.hs

\

列表和元组的区别 即

[1,2,3] 和 (1,”2”, 三)的区别..

[1,2..5] 省略号定义数组二个冒号;

1:[1,2] 前增扩展数组。。

IO

<- 将 io string 转换为string .

:cd d:\haskexam

Prelude> saf<-readFile "output.txt"

saf :: String

saf

"E23E4QWREWQRWQR\n"

ad<-getLine 可以让用户输入ad变量的值

读取文件内容并显示;

readFile "D:\\haskexam\\1.txt"

putStrLn "fas"

fas

LET

let ad="asd" 给变量赋值;

prelude

lines "asd\nadsad"

根据换行符将一个字符串分为多个字符串

length [1,2] 数组的长度

show 1234 将数字转换为字符显示

"1234"

print 213 显示

213

Compare 比较大小

Head 、 tail 、take、drop 、last列表的操作‘

Fst 、snd 元组的操作

定义函数;

定义一个新的数据结构

定义枚举。

data Roygbiv = Red

| Orange

| Yellow

| Green

| Blue

| Indigo

| Violet

deriving (Eq, Show)

报错

error "dasdfas"

*** Exception: dasdfas

Break :分割列表

碰到奇数分为二个列表;

all &any

all odd [1,3,5]

True

isPrefixOf [2] [2,4]

isSuffixOf "24" "2342t4"

zip [1,2,3] [4,5]

[(1,4),(2,5)]

:module -Data.List

Prelude Data.List>zipWith (+) [1,2,3] [4

[5]

words "das asd asd"

["das","asd","asd"]

unwords ["jumps", "over", "the", "lazy", "dog"]

"jumps over the lazy dog"

let ad = map toLower "D A"

map toUpper "dasd ads"

map negate [1,2,3]

[-1,-2,-3]

map (dropWhile isSpace) [" a","f"," e"]

["a","f","e"]

zip3 "foo" "bar" "quux"

[('f','b','q'),('o','a','u'),('o','r','u')]

map (+3) [24,36]

[27,39]

(`elem` ['a'..'z']) 'f'

True

(init.tail) "fas"

"a"

(init.tails) "fas"

["fas","as","s"]

map isUpper "fdfD"

[False,False,False,True]

isUpper (head "ad")

--多行注释 单行注释;

Prelude> {-

Prelude| asd

Prelude| asd

Prelude| -}

//

:show imports

标准引导库 Prelude.hs

error "fa"

*** Exception: fa

div 4 2

2

Mod

Negate

Abs

'\98'

'b'

1.2e3

1200.0

[2*n | n<-[2..14] , odd n]

[2*n | n<-[2..14] , n>5]

[m+n | (m,n)<-[(1,2),(3,4)] ]

复制;

replicate 3 'f'

"fff"

it :: [Char]

(0.02 secs, 0 bytes)

1:[1]

[1,1]

[1]++[2]

[1,2]

[1,2]!!0

1

concat [[1,2,33],[4,5]]

[1,2,33,4,5]

or [True, False]

True

let x=5 in x^2+2*x

35

let squartwo n m = sqn+sqm

Prelude| where

Prelude| sqn = n*n

Prelude| sqm = m*m

Prelude|

squartwo :: Num a => a -> a -> a

(0.00 secs, 0 bytes)

Prelude> squartwo 2 3

13

sum [2..6]

20

concat ["1","2"]

"12"

let doubleAll xs = [2*x|x<-xs]

Prelude|

doubleAll :: Num t => [t] -> [t]

(0.00 secs, 0 bytes)

Prelude> doubleAll[2,3]

[4,6]

map (+3) [1,2,3]

[4,5,6]

let add a b = a+b

map (add 2) [1,2]

[3,4]

map (replicate 2) [1,2,3]

[[1,1],[2,2],[3,3]]

map fst [(1,2),(3,5),(6,3),(2,6),(2,5)]

[1,3,6,2,2]

[x+3|x<-[1,2,3]]

[4,5,6]

Data.List;

intersperse '_' "faf"

"f_a_f"

intercalate "fs" ["12","34"]

"12fs34"

transpose [[1,2],[3,4],[6,7]]

[[1,3,6],[2,4,7]]

map sum $ transpose [[0,3,5,9],[10,0,0,9],[8,5,1,-1]]

[18,8,6,17]

map sum (transpose [[0,3,5,9],[10,0,0,9],[8,5,1,-1]] )

sum [1,2,5]

8

concat ["24", "3"]

"243"

concat $ map (replicate 4) [1..3]

[1,1,1,1,2,2,2,2,3,3,3,3]

concatMap (replicate 4) [1..3]

[1,1,1,1,2,2,2,2,3,3,3,3]

take 6 $ iterate (*3) 2

[2,6,18,54,162,486]

splitAt 3 "heyman"

("hey","man")

takeWhile (>3) [6,5,4,3,2,1,2,3,4,5,4,3,2,1]

[6,5,4]

'f'/='g'

True

'f'=='g'

False

takeWhile (<10000) $ map (^3) [1..]

[1,8,27,64,125,216,343,512,729,1000,1331,1728,2197,2744,3375,4096,4913,5832,6859,8000,9261]

span (/='i') "this"

("th","is")

break (=='i') "thisis"

("th","isis")

sort [14,3,54]

[3,14,54]

reverse $sort [14,3,54]

[54,14,3]

group ["1","1", "3"]

[["1","1"],["3"]]

zip [1,2,5] [3,4]

[(1,3),(2,4)]

let x=[1,2] in sum x

3

isInfixOf "cat" "catda"

True

"hey" `isPrefixOf` "hey there!"

True

"hey" `isPrefixOf` "f hey there!"

False

"there!" `isSuffixOf` "oh hey there!"

True

"there!" `isSuffixOf` "oh hey there! f"

False

elem 1 [1,2,3]

True

elem 11 [1,2,3]

False

partition (>3) [1,3,5,6,3,2,1,0,3,7]

([5,6,7],[1,3,3,2,1,0,3])

let bign n = if n>0 then True else False

let ds = partition (bign) [-5,1,3,5,6,3,2,1,0,3,7]

ds

([1,3,5,6,3,2,1,3,7],[-5,0])

partition (`elem` "AB") "BOBsidneyMORGANeddy"

("BBA","OsidneyMORGNeddy")

find (=='f') "gasdf"

Just 'f'

find (=='f') "gasdgd"

Nothing

'f' `elem` "gas"

False

elemIndex 11 [1,2,3]

Nothing

elemIndex 1 [1,2,3]

Just 0

elemIndices 1 [1,2,3,1]

[0,3]

findIndices (=='f') "gasdgfdf"

[5,7]

findIndex (=='f') "gasdgfdf"

Just 5

zip [1,2] [3,4,5]

[(1,3),(2,4)]

zip [1,2,3,4,5] [3,4,5]

[(1,3),(2,4),(3,5)]

zip4 [2,3,3] [2,2,2] [5,5,3] [2,2,2]

[(2,2,5,2),(3,2,5,2),(3,2,3,2)]

zipWith (+) [1,2,3] [4,5,2,2]

[5,7,5]

lines "first line\nsecond line\nthird line"

["first line","second line","third line"]

unlines ["first line", "second line", "third line"]

"first line\nsecond line\nthird line\n"

words "first li ne"

["first","li","ne"]

words "first line"

["first","line"]

unwords ["first","li","ne"]

"first li ne"

nub [1,3,2,4,3,2,1,2,3,4,3,2,1]

[1,3,2,4]

nub "Lots of words and stuff"

"Lots fwrdanu"

delete 'h' "hey there ghang!"

"ey there ghang!"

delete 'h' $ delete 'h' $ "hey there ghang!"

[1,2] \\ [2,3,4]

[1]

[2,3,4] \\[1,2]

[3,4]

union [1,2,3] [2,3,4]

[1,2,3,4]

[1,2,3] `intersect` [2,3,4]

[2,3]

insert 4 [15,2,2,3,5,6,7]

[4,15,2,2,3,5,6,7]

insert 4 [2,2,3,5,6,7]

[2,2,3,4,5,6,7]

insert 3 [1,2,4,3,2,1]

[1,2,3,4,3,2,1]

groupBy登场! 它取一个含两个参数的函数作为参数来判定相等性.

let values = [1,2,3,-3,-2,1,2,3,-3,-2]

let compaire2Num x y = if (x*y > 0 ) then True else False

groupBy ( compaire2Num ) values

[[1,2,3],[-3,-2],[1,2,3],[-3,-2]]

groupBy :: (a -> a -> Bool) -> [a] -> [[a]]

functor a,a 返回Bool;

入参为【a】,出差为【【a】】

group [1,1,1,2,2,3]

[[1,1,1],[2,2],[3]]

let sortGT a b = if a< b then GT else LT

sortBy sortGT values

[3,3,2,2,1,1,-2,-2,-3,-3]

let xval = [13,12,3]

sortBy sortGT xval

Data.Char

Prelude Data.List> :m Data.Char

Prelude Data.Char> :t group

Prelude Data.Char> import Data.List

(0.00 secs, 0 bytes)

Prelude Data.Char Data.List>

isControl '、'

False

isSpace ' '

True

isLower 'a'

True

isUpper 'A'

True

isAlpha 'a'

True

isAlpha '4'

False

isAlphaNum '1'

True

isPrint 'f'

True

isDigit '2'

True

isOctDigit '7'

True

isOctDigit '8'

False

isHexDigit 'g'

False

isHexDigit 'e'

True

isLetter '$'

False

isNumber '1'

True

isPunctuation ';'

True

isSymbol '$'

True

isAscii '&'

True

all isLetter "gdff"

True

all isLetter "gd2f"

False

generalCategory 'a'

LowercaseLetter

map generalCategory "f1'$"

[LowercaseLetter,DecimalNumber,OtherPunctuation,CurrencySymbol]

map toUpper "fa2"

"FA2"

map toTitle "gfa das"

"GFA DAS"

digitToInt 'f'

15

intToDigit 15

'f'

ord '%'

37

chr 97

'a'

Prelude Data.Char Data.List> let encode shift msg = map chr $ map (+ shift) ords

Prelude Data.Char Data.List| where ords = map ord msg

Data.Map

Prelude Data.Char Data.List> import

(0.02 secs, 551624 bytes)

Prelude Data.Char Data.List Data.Map>

Prelude.filter odd [2,4,1,3,6,8,5,7]

:t Data.Map.filter

Data.Map.filter :: (a -> Bool) -> Map k a -> Map k a

fromList [("betty","555-2938"),("bonnie","452-2928"),("lucille","205-2928")]

Loading package array-0.4.0.1 ... linking ... done.

Loading package deepseq-1.3.0.1 ... linking ... done.

Loading package containers-0.5.0.0 ... linking ... done.

fromList [("betty","555-2938"),("bonnie","452-2928"),("lucille","205-2928")]

fromList [(1,2),(3,4),(3,2),(5,5)]

fromList [(1,2),(3,2),(5,5)]

去掉重复key的

import qualified Data.Map as Map

Map.insert 3 100 Map.empty

fromList [(3,100)]

Map.insert 5 600 (Map.insert 4 200 ( Map.insert 3 100 Map.empty))

fromList [(3,100),(4,200),(5,600)]

let am = Map.empty

Map.insert 3 100 am

fromList [(3,100)]

Map.null Map.empty

True

let am = Map.fromList [(2,4),(3,3),(4,2),(5,4),(6,4)]

Map.size am

5

Map.singleton 3 9 $ Map.insert 5 9

:368:1:

Couldn't match expected type `(Map k1 a1 -> Map k1 a1) -> t0'

with actual type `Map k0 a0'

The first argument of ($) takes one argument,

but its type `Map k0 a0' has none

In the expression: singleton 3 9 $ Data.Map.insert 5 9

In an equation for `it': it = singleton 3 9 $ Data.Map.insert 5 9

Map.insert 5 9 $ Map.singleton 3 9

fromList [(3,9),(5,9)]

am

fromList [(2,4),(3,3),(4,2),(5,4),(6,4)]

Map.lookup 2 am

Just 4

Map.member 2 am

True

Map.map (*100) am

fromList [(2,400),(3,300),(4,200),(5,400),(6,400)]

Map.map (>0) am

fromList [(2,True),(3,True),(4,True),(5,True),(6,True)]

Map.filter (>3) am

fromList [(2,4),(5,4),(6,4)]

Map.fromListWith max [(2,3),(2,4),(2,1)]

fromList [(2,4)]

Map.fromListWith (+) [(2,3),(2,4),(2,1)]

fromList [(2,8)]

Map.insertWith (+) 3 100 $ Map.fromList [(3,4),(5,103),(6,339)]

fromList [(3,104),(5,103),(6,339)]

Map.insertWith (-) 5 100 $ Map.fromList [(3,4),(5,103),(6,339)]

fromList [(3,4),(5,-3),(6,339)]

Data.Set

import qualified Data.Set as Set

let text1 = "I just had an anime dream,Anime..,Reality..,Are they so different?"

let set1 = Set.fromlist text1

set1

fromList " ,.?AIRadefhijlmnorstuy"

Set.intersection set1 set2

Set.difference set1 set2

Set.union set1 set2

Set.null Set.empty

True

Set.null set1

False

Set.insert 4 $ Set.fromList [9,3,8,1]

fromList [1,3,4,8,9]

Set.delete ' ' $Set.delete 'a' aa

Set.fromList [2,3,4] `Set.isSubsetOf` Set.fromList [1,2,3,4,5]

True

Set.fromList [1,2,3,4,5] `Set.isProperSubsetOf` Set.fromList [1,2,3,4,5]

Set.map (+1) $ Set.fromList [1,2,3,4,5]

Set.filter odd $ Set.fromList [3,4,5,6,7,2,3,4]

:cd d:\haskexam

:load geometry.hs

module Geometry

(

sphereVolume

,sphereArea

,cubeVolume

,cubeArea

,cuboidArea

,cuboidVolume

) where

sphereVolume :: Float -> Float

sphereVolume radius = (4.0 / 3.0) * pi * (radius ^ 3)

data Shape = Circle Float Float Float | Rectangle Float Float Float Float deriving (Show)

let surface (Circle _ _ r) = pi * r ^ 2

surface $ Circle 10 20 10

314.15927

Data.List.map (Circle 10 20) [4,5,6,6]

[Circle 10.0 20.0 4.0,Circle 10.0 20.0 5.0,Circle 10.0 20.0 6.0,Circle 10.0 20.0 6.0]

//取得愿的半径

let radiusCircle (Circle _ _ r) = r

radiusCircle $ Circle 1 1 2

2.0

data Circle = Circle{x::Float,y::Float, radius::Float} deriving (Show)

x $Circle 2 3 4

2.0

data Person = Person {age::Int, name::String} deriving (Show,Eq)

read "1"::Int

1

compare 2 3

LT

compare True False

GT

True > False

True

deriving (Eq, Ord, Show, Read, Bounded, Enum)

小写的不行

data ab = abc| efg

:67:11: Not a data constructor: `abc'

首字母大写ok.

data AB = ABS| EFG

data AB = ABS | EFG

它也是Enmu的实例,可以得到前一天和后一天,并且可以对此使用List的区间。

ghci> succ Monday

Tuesday

ghci> pred Saturday

Friday

x<-getLine

foldr (*)3 [1 ,2,3]

18

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 206,378评论 6 481
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 88,356评论 2 382
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 152,702评论 0 342
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 55,259评论 1 279
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 64,263评论 5 371
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,036评论 1 285
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,349评论 3 400
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,979评论 0 259
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 43,469评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,938评论 2 323
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,059评论 1 333
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,703评论 4 323
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,257评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,262评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,485评论 1 262
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,501评论 2 354
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,792评论 2 345

推荐阅读更多精彩内容

  • Scala的集合类可以从三个维度进行切分: 可变与不可变集合(Immutable and mutable coll...
    时待吾阅读 5,802评论 0 4
  • SwiftDay011.MySwiftimport UIKitprintln("Hello Swift!")var...
    smile丽语阅读 3,827评论 0 6
  • 自古就有“男儿有泪不轻弹”,“男儿膝下有黄金”的说法。这就赋予了男人们坚强,隐忍,不易于女人们那般柔弱易流泪的形象...
    清泠之声阅读 4,629评论 44 25
  • 夏季,岁月是绚烂的颜色。走进夏天,南风送爽,一汪绿意映入眼帘,浓淡两相宜。入心,一片绿茵茵的清新,沁人心脾,独我钟...
    门前折柳阅读 273评论 0 0
  • 我希望的是 我们彼此都是能战斗的人 不要抛出一个又一个怎么办 我又能怎么办? 我也有很多无助的时候 但怎么办这个字...
    雾与lyu阅读 243评论 0 0