haskell笔记2

模式匹配

# haskell_test.hs
length' :: [a] -> a
length' [] = 0
length' (_:x) = 1 + length' x

as模式

xs@x:y:ys
xs代表整个list
x代表一部分
方便引用原值,而非分割的
capital :: String -> String
capital "" = "empty"
capital xs@(x:y) = "the first of  " ++ xs ++ " is " ++  x;

 guard

# bmi eg

bmiTell weight height
| weight / height ^ 2 <= 18.5 = "you are thin."
| weight / height ^ 2 <= 25 = "you are nomal."
| weight / height ^ 2 <= 30 = "you are fat."
| otherwise = "you are fat to die."

有重复。可改为

bmiTell weight height
| bmi <= thin = "you are thin."
| bmi <= nomal = "you are nomal."
| bmi <= fat = "you are fat."
| otherwise = "you are fat to die."

where bmi = weight / height ^ 2

  thin = 18.5

  nomal = 25

  fat = 30

 let

let (a,b) = (2,3) in a^2 + b

 case 模式匹配的语法糖

head' :: [a] -> a
head' [] = error "error"
head' (x:_) = x

等价于

head' :: [a] -> a
head' xs = case xs of [] -> error "error"
                               (x:_) -> x

 

转载于:https://www.cnblogs.com/guochunyi/p/5981205.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值