-- This is the function we're trying to implement
evenSquares :: [Int] -> [Int]
-- We could start by noting that `if` expression has a nice name,
-- which can be factored out to make things look cleaner
-- Same implementation as Willem's
evenSquares xs = [ squareIfEven x | x <- xs ] where
squareIfEven x = if even x then x * x else x
-- List comprehensions are nice, but there's also another name for what we're doing,
-- which is mapping over a collection of values and applying a method
evenSquares xs = map squareIfEven xs where
squareIfEven x = if even x then x * x else x
-- Note how the `xs` is an argument to `evenSquares` and also the last argument to `map`
-- We can actually get rid of `xs` entirely via this rule:
-- https://wiki.haskell.org/Eta_conversion
evenSquares = map squareIfeven where
squareIfEven x = if even x then x * x else x
-- This one's a bit of a stretch, but conceptually quite useful
-- The idea of 'apply a method if a condition is true' can be expressed as a method
-- which takes a predicate method, a transformation method, and a value
-- We can leverage this ourselves to make `squareIfEven` more generic too
evenSquares = map (if' even square id) where
square x = x * x
if' pred fst snd x = if pred x then fst x else snd x
-- There's a bunch more solutions we can try, including things like `do` notation
-- This is just an idea of how you could look at your problem
-- Pick one which makes your solution clear and concise!
2条答案
按热度按时间bttbmeg01#
你在这里 filtering。你应该确定这个数是奇数还是偶数,然后求平方,这可以在列表解析的yield部分完成。
但是类型签名提示你根本不需要构造一个列表,你只需检查参数
x
是否为偶数,如果是,则返回x*x
,否则返回x
:或通过防护装置:
ylamdve62#
一个非常简单的答案是,你可以直接将一个
if
语句嵌入到你的列表理解中,如下所示:这是可能的,因为
if
是Haskell中的表达式,意味着它求值为一个值,所以类似如下的内容是有效的:从另一个Angular 来看这个问题也是很好的。列表解析可能很好,但是在其中插入一个
if
可能会变得很混乱。Willem分解出方法的解决方案很好,所以让我们看看在代码中利用它的其他方法: