我需要返回给定范围内所有偶数的正方形列表。因此,它的功能是“平方低高”。输入和输出的例子是平方1 6= 4,16,36。到目前为止,我认为我的逻辑是合理的,但由于我对Haskell非常陌生,我不知道这里到底出了什么问题,
Squares low high =
let aux xxs low high
| ([rem low 2] /= 0) = aux xxs (1 + low) high
| ([rem low 2]==0) = aux ([low * low] ++ xxs) (1 + low) high
| otherwise = xxs
in aux [] low high任何帮助都将不胜感激。
发布于 2014-03-14 19:29:06
Squares low high = -- ...这一行已经中断了,因为只有类型/模块可以以大写字母开头。
let aux xxs low high
| ([rem low 2] /= 0) = aux xxs (1 + low) high
| ([rem low 2]==0) = aux ([low * low] ++ xxs) (1 + low) high
| otherwise = xxs给aux打电话要多长时间?只有在点击otherwise时才停止递归。但是整数要么是偶数,要么是奇数,所以你永远不会返回xss。相反,您需要检查是否是low > high。
请注意,您可以在没有辅助函数的情况下定义squares:
squares low high
| low > high = []
| even low = low*low : squares (low + 1) high
| otherwise = squares (low + 1) high或者使用map和filter
squares low high = map (^2) . filter even $ [low..high]或者列表理解(这基本上是map和filter的语法糖):
squares low high = [x^2| x <- [low..high], even x]发布于 2014-03-14 19:29:13
看起来你是在做这样的事:
squares :: Int -> Int -> [Int]
squares low high = aux [] low high
where aux xxs low high
| low > high = xxs
| rem low 2 /= 0 = aux xxs (1 + low) high
| otherwise = aux (xxs ++ [low * low]) (1 + low) high你的警卫有几个原因错了。首先,[rem low 2]是一个[Int],而不是Int,所以您需要去掉方括号。其次,您的otherwise子句将永远不会到达,因为前两种情况中的一种必须是正确的。你应该把终止支票移到开头。
您还在按错误的顺序构建输出列表--如果希望下一个值位于末尾,则在添加新元素时应使用xxs ++ [low * low]。注意,使用++构建列表效率很低,最好使用(:)将元素从前面添加到列表中。
最后,您可以使用map和filter以一种简单得多的方式来完成这一任务。
squares low high = map (\x -> x * x) . filter even $ [low .. high]或一份清单的理解:
squares low high = [x * x | x <- [low .. high], even x]发布于 2014-03-14 19:40:28
生成从low到high的数字
gen a b = a : gen (a+1) b对吧?..。不,错了:它并没有停止。我们能加上停车条件吗?
gen a b | ..... = []
| otherwise = a : gen (a+1) b如果我们只想要偶数呢?
gen a b | ..... = []
| rem ... ... == 0 = a : gen (a+1) b
| otherwise = .....很容易把它调整成正方形。但是,我们真的需要测试我们自己产生的数字吗?如果a是偶数呢?
gen a b | even a = g a
where
g a | ..... = []
| otherwise = a : g (a+2) -- only evens are generated如果很奇怪呢?.
https://stackoverflow.com/questions/22413766
复制相似问题