【发布时间】:2020-08-08 19:54:37
【问题描述】:
正如标题中所说,例如我有这个函数当然会引发错误:
bhaskara a b c =
if discriminant >= 0 then (x1,x2) else str_disc
where
discriminant = (b^2 - (4*a*c))
str_disc = "the discriminant is less than zero"
x1 = ((-b) - sqrt (b^2 - (4*a*c))) / (2*a)
x2 = ((-b) - sqrt (b^2 - (4*a*c))) / (2*a)
我听说你可以使用自定义数据类型,所以我想这样做,但我显然在这里做错了:
data Result = (Double, Double) | String
bhaskara :: Double -> Double -> Double -> Result
bhaskara a b c =
if discriminant >= 0 then (x1,x2) else str_disc
where
discriminant = (b^2 - (4*a*c))
str_disc = "the discriminant is less than zero"
x1 = ((-b) - sqrt (b^2 - (4*a*c))) / (2*a)
x2 = ((-b) - sqrt (b^2 - (4*a*c))) / (2*a)
有人可以展示如何解决这个问题吗?
顺便说一下,我不包括判别式等于零的情况
【问题讨论】:
-
需要使用数据构造函数,例如
data Result = Values Double Double | Error String -
Bhaskar 是一个很酷的 func 名称,它意味着什么吗?
-
@Evgeny 哈哈,是的,我知道这是什么意思,这只是这个人的公式en.wikipedia.org/wiki/Bh%C4%81skara_II 让你找到二次方程的根
-
酷,感谢链接!我不知道是谁先提出来的。这是我们高中课程中一个无名的公式。总体而言,您提议的任何一个都很好。