作为学习Haskell的练习,我决定尝试使用GSL库翻译我用C编写的一些作业。作为绝对的初学者,我在许多事情上磕磕绊绊。
我不确定以下是缩进错误还是我没有正确使用if语句,Google也没有帮助。我的目标是编码正态分布的累积分布函数。 (参见编辑更精简的版本)
以下是代码:
import Bindings.Gsl.MathematicalFunctions
cdf_normal_as :: x -> fx (Double, Double)
let {
fx = 0;
psi_x = 0;
y = 0;
b = 0.2316419;
a1 = 0.319381530;
a2 = (-0.356563782);
a3 = 1.781477937;
a4 = (-1.821255978);
a5 = 1.330274429;
}
if x >= 0
then
let
y = 1 / ( 1 + b * x );
psi_x = ( 1 / ( sqrt( 2 * M_PI) ) ) * exp ( -(pow(x,2) / 2 ));
in
fx = 1.0 - psi_x * ( a1 * y + a2 * y * y + a3 * y * y * y + a4 * y * y * y * y + a5 * y * y * y * y * y );
else
let
x = x * (-1);
y = 1 / ( 1 + (b * x));
psi_x = (1 / (sqrt(2 * M_PI) ) ) * exp( -(pow(x,2)/2 ) );
in
fx = 1 - psi_x * (a1*y + a2*pow(y,2) + a3*pow(y,3) + a4*pow(y,4) + a5*pow(y,5));
cdf_normal_as fx;
这是我得到的信息:
Prelude> :l Normal_CDF.hs
[1 of 1] Compiling Main ( Normal_CDF.hs, interpreted )
Normal_CDF.hs:20:1:
parse error (possibly incorrect indentation or mismatched brackets)
Failed, modules loaded: none.
Prelude>
我做错了什么?
---------------------------------------编辑
我做了一个更精简的版本,以便更好地了解可能存在的问题。 我的问题是:在Haskell中执行等效的if-else语句的正确和最佳方法是什么?
以下代码应该接受y变量,将某个变量x设置为常量,然后在执行特定任务之前检查y是大于还是小于0(如果是或不是)。这编译。
plus_or_double :: Double -> Double
plus_or_double y = let {
x = 2;
} in case ( y>= 0 ) of
True -> ( x + y )
False -> y
我已经使用了case语句,因为我无法使if语句有效,尽管必须有更好的方法......
答案 0 :(得分:3)
这是一个有效的简单示例。我认为你需要let { ...
左侧的内容:
module Main where {
test :: Double -> Double;
test x = let {
first = let {
a = x;
b = a + x*x;
} in a+b;
second = x*x*x;
} in first + second;
main = do
print $ test 5
}
请参阅Haskell Wikibook : Explicit characters in place of indentation