我想得到给定列表的总距离,其中包含Floats元组。我必须保证少于2个元素的列表将输出0.0
我到目前为止所做的是:
distancia :: [(Float,Float)] -> Float
distancia [] = 0.0
distancia [(_,_)] = 0.0
distancia (x:y:xs) = foldl(\(xa,ya)(xb,yb) -> sqrt(((xa-xb)**2)+((ya-yb)**2))) 0 xs
Run Code Online (Sandbox Code Playgroud)
所以我期望的输出是
ghci> distancia [(0,0), (0,0), (1,0), (1,10)]
11.0
ghci> distancia [(1,1), (3,4)]
3.6055512
Run Code Online (Sandbox Code Playgroud)
但是我收到以下错误:
t3_fc42035.hs:9:22: error:
* Couldn't match expected type `Float'
with actual type `(Float, Float)'
* In the expression:
foldl
(\ (xa, ya) (xb, yb) -> sqrt (((xa - xb) ** 2) + ((ya - yb) ** 2)))
0
xs
In an equation for `distancia': …Run Code Online (Sandbox Code Playgroud) 因此,基本上,我对ym作业有一个疑问:“使用前奏函数创建一个检查列表是否为空的函数”,我看到了null函数,我想使用它并打印消息。所以我尝试了以下方法:
notEmpty :: [Int] -> [Char]
notEmpty [x] = if (null[x]) then "False" else "True"
Run Code Online (Sandbox Code Playgroud)
如果我调用notEmpty [],它会给我这个错误:经过几次学习后,函数notEmpty中的Non.Exhaustive模式出现了:
notEmpty :: [Int] -> [Char]
notEmpty [] = "False"
notEmpty [x] = if (null[x])then "False" else "True"
Run Code Online (Sandbox Code Playgroud)
但是在此之后,我尝试了以下输入:notEmpty [1,2],它给了我同样的错误。
我的问题是,当我运行null [1,2]时,它给我错误,那么我在做什么错呢?