Haskell示例

i :: Int
i = 5

--add, sub :: Int -> Int -> Int
add, sub :: (Num a) => a -> a -> a
add a b = a + b
sub a b = a - b

f :: (Num a) => a -> a
f x = 4 * x + 1

--出错
--area :: (Num x) => Floating -> x -> x
area :: Floating a => a -> a
area r = pi * (r ^ 2)

fun :: (Num a) => (a, a) -> a
fun (x,y) = 4 * x + 5 * y + 1

fun' :: (Num a) => a -> a-> a
fun' x y = 4 * x + 5 * y + 1

--Lambda表达式
--fun'' = \x -> \y -> 4 * x + 5 * y + 1
fun'' :: Num a => a -> a ->a
fun'' = \x y -> 4 * x + 5*y + 1

plus :: Num a => a -> a -> a
plus = (+)

--参数绑定
--area_tri :: Float -> Float -> Float -> Float
area_tri ::  Floating a => a -> a -> a -> a
-- let ... in
area_tri a b c = let p = (a+b+c)/2 in  sqrt (p * (p-a) * (p-b) * (p-c))

area_tri' :: Double -> Double -> Double -> Double
-- where
area_tri' a b c = 
    sqrt (p * (p-a) * (p-b) * (p-c))
    where 
    p = ((a + b + c) / 2.0)

--条件表达式
isTwo :: Int -> Bool
isTwo x = if x == 2 then True else False

isTwo' :: Int -> Bool
isTwo' = (==2)

 

posted @ 2014-10-11 16:17  庚武  Views(479)  Comments(0Edit  收藏  举报