您的位置:首页 > 其它

haskell 笔记

2015-10-09 08:49 417 查看
:set editor gedit

:edit hello.hs

在跳出的gedit里面输入

main = putStrLn "Hello World!"

:! ghc --make "hello.hs" 编译

新建shell,输入./hello 即可运行

hello.hs:

area' :: Double ->Double

area' =(\x->pi*x^2)

输入area'5 得到 78.53981633974483

:module

取消load

先输入:!, 然后就可以输入DOS命令并执行. 比如输入:!dir查看当前的工作目录



roots :: Double->Double->Double->(Double,Double)

roots a b c =((-b+sqrt(b^2-4*a*c))/(2*a),((-b-sqrt(b^2-4*a*c))/(2*a)))

*Main> roots( -10) 33 3

(-8.853386507137095e-2,3.3885338650713708)

lanta 表示法

delta:: Double->Double->Double->Double

delta =(\a b c->sqrt(b^2-4*a*c))

roots:: Double->Double->Double->(Double,Double)

roots =(\a b c-> ( (-b-delta a b c)/(2*a),(-b+delta a b c)/(2*a) ) )

Patterns(模式表示法):

cons 0 = 0

cons 1 = 1

cons otherwise = 2

cons x = 2

cons _ = 2

fi::Integer->Integer

fi 0 = 0

fi 1 = 1

fi n = fi(n-1)+fi(n-2)

Guard:(守卫)

sign x | x>0 =1

| x==0 =0

| x<0 =(-1)

case表示法:

cons1 n = case n of

0 -> 0

1 -> 1

n -> 2

cons2 n =case n of {0->0;1->1;_->2;}

if语句:

sign1 x = if x>0 then 1 else if x==0 then 0 else -1

局部声明:

在函数中用 let in 减少重复计算,delta 和 twice_a 对齐

roots a b c =let delta=sqrt(b*b-4*a*c)

twice_a=2*a

in ((-b-delta)/twice_a,(-b+delta)/twice_a)

也可以使用where

roots2 a b c = ((-b-delta)/twice_a,(-b+delta)/twice_a)

where delta=sqrt(b*b-4*a*c)

twice_a=2*a

(let (a,b,c)=(1,2,3) in a+b+c) * 100

600

(let a=1;b=2;c=3 in a*b*c,let f="Hey ";g="Tom" in f++g)

(6,"Hey Tom")

[if 5>3 then "5>3" else "5<=3" ,if 'a'>'b' then "a>b" else "a<=b"]

["5>3","a<=b"]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: