Haskell中偶数的平方

cgvd09ve  于 2022-11-14  发布在  其他
关注(0)|答案(2)|浏览(117)

我试图写一个基本的函数在 haskell 如下所示。我的目的是提供的代码平方只有偶数,而奇数将保持不变。请帮助我关于这个问题。

square:: Int -> Int
square x = [ x*x | x <- [1..10], mod x 2 == 0 ]

问候

bttbmeg0

bttbmeg01#

你在这里 filtering。你应该确定这个数是奇数还是偶数,然后求平方,这可以在列表解析的yield部分完成。
但是类型签名提示你根本不需要构造一个列表,你只需检查参数x是否为偶数,如果是,则返回x*x,否则返回x

square:: Int -> Int
square x = if even x then x*x else x

或通过防护装置:

square:: Int -> Int
square x
  | even x = x*x
  | otherwise = x
ylamdve6

ylamdve62#

一个非常简单的答案是,你可以直接将一个if语句嵌入到你的列表理解中,如下所示:

[ if even x then x * x else x | x <- [1..10] ]

这是可能的,因为if是Haskell中的表达式,意味着它求值为一个值,所以类似如下的内容是有效的:

let _ = if 1 + 1 == 2 then "foo" else "bar"

从另一个Angular 来看这个问题也是很好的。列表解析可能很好,但是在其中插入一个if可能会变得很混乱。Willem分解出方法的解决方案很好,所以让我们看看在代码中利用它的其他方法:

-- 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!

相关问题