【问题标题】:How to simplified this function in Haskell?如何在 Haskell 中简化此功能?
【发布时间】:2020-05-09 05:54:22
【问题描述】:

我认为以这种方式编写代码是多余的。不管类型构造函数是什么,返回值都是一样的。有没有办法一次性写入返回值?

data End = Leftend (Int,Int) | Rightend (Int, Int)
            deriving (Eq, Ord, Show)


cmp:: End->End->Ordering
cmp (Leftend (l, h1))  (Rightend (r,h2))
        | l < r = LT
        | l == r = EQ
        | l > r = GT
cmp (Leftend (l, h1))  (Leftend (r,h2))
        | l < r = LT
        | l == r = EQ
        | l > r = GT
cmp (Rightend (l, h1))  (Rightend (r,h2))
        | l < r = LT
        | l == r = EQ
        | l > r = GT
cmp (Rightend (l, h1))  (Leftend (r,h2))
        | l < r = LT
        | l == r = EQ
        | l > r = GT

【问题讨论】:

  • 这并不完全是重复的,但与stackoverflow.com/questions/32158110/…有很多相同的地方。
  • 我建议将您的数据声明重构为 data Side = Left | Right; data End = End { side :: Side, width :: Int, height :: Int } 或类似的东西。然后cmp = comparing width,可能连名字都不值得。
  • 对于初学者来说,这种不断出现的模式| l &lt; r = LT | l == r = EQ | l &gt; r = GT只是compare l r

标签: haskell functional-programming pattern-matching


【解决方案1】:

我猜……

import Data.Ord

discard :: End -> (Int, Int)
discard (Leftend v) = v
discard (Rightend v) = v

cmp :: End -> End -> Ordering
cmp = comparing (fst . discard)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-14
    • 1970-01-01
    相关资源
    最近更新 更多