haskell 笔记2

1. hakell has type inference(类型推导)

  1. :t command
// use command :t (short for type) to examine the type of a expression

:t False
>> False :: bool

:t 'a'
>>'a':: char

:t 4==5
>> 4==5 :: bool
//:: is read as "has a type of"

2 give function a type

uppercase :: [Char]->[Char]
//it means this function has a map from string to string
uppercase xs = [c|c<-xs,c `elem` ['A'..'Z']]

2 typeclass

2.1 definition
A typeclass is a sort of interface that defines some behavior. If a type is a part of a typeclass, that means that it supports and implements the behavior the typeclass describes. A lot of people coming from OOP get confused by typeclasses because they think they are like classes in object oriented languages. Well, they’re not. You can think of them kind of as Java interfaces, only better.
typeclass 是一种定义行为的接口,如果一种type属于一个typeclass,那么它支持这个typeclass的行为。很多人认为这与面向对象中的class类似,但事实并不是。你可以认为他们是类似于java的interfaces,只不过更好。
2.2 Eq,Ord classtype

:t (==)
>>(==)::(Eq a)=> a->a->Bool
//=> symbol is called a class constraint.
//(Eq a) means a belongs the Eq typeclass,The Eq typeclass provides an interface for testing for equality
// there is other typeclass like Ord(testing for ordering)
:t (>)
>>(>) :: Ord a => a -> a -> Bool

2.3 Show,Read classtype

//show typeclass,convert a type variable into string
:t show
>>show :: Show a => a -> String

//read typeclass,convert a string into a type variable
:t read
>>read :: Read a => String -> a

2.3.1 a error while using read

read "4"
>> error

because compiler can’t infer the type of a,so it doesn’t know what kind of type it shold’t convert string into
two correct ways to use read
first is to do something about the result,then copiler can infer the type of a

read "5" + 2
>>3
// this infer that we need read to return a int

second way is to directly tell the compiler what kind type of a

read "5" :: Int
>>5
// remember :: means has a type of 
//"5" has a type of Int

2.4 Num(整数和小数),Integral(整数),Floating(包括浮点)
fromintegral方法

:t fromIntegral
>>fromIntegral :: (Num b, Integral a) => a -> b
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值