繁体   English   中英

Haskell:查找自定义数据类型中的最小值

[英]Haskell: Find the minimum in custom data type

因此,我有一个自定义数据类型,我们将其称为Struct ,定义如下:

data Struct = Struct  [SubStruct] deriving (Read, Show)
data SubStruct = SubStruct (Int, Int) deriving (Read, Show)

我需要做的是遍历Struct所有元素,然后根据fst然后根据snd找到最小值。 我怎么做? 更具体地说,我想获得另一个SubStruct例如:

SubStruct (-2,-5) ,基于代码中的示例。

目前,我首先这样做:

import Data.List
import Data.Function (on)
import Data.List (sortBy)

data Struct = Struct  [SubStruct] deriving (Read, Show)
data SubStruct = SubStruct (Int, Int) deriving (Read, Show  )

struct s sx = Struct(s:sx)

subStruct :: (Int, Int) -> SubStruct
subStruct (x, y) = SubStruct (x, y)

substructs = Struct $ [subStruct (0,1), subStruct (-2, 3), subStruct (4,-5)]

results xs = sortBy (compare `on` fst) (substructs xs)

但是我得到这个错误:

Couldn't match expected type `t -> [(a, b)]'
            with actual type `Struct'
Relevant bindings include
  xs :: t (bound at bbox.hs:15:9)
  results :: t -> [(a, b)] (bound at file.hs:15:1)
The function `substructs' is applied to one argument,
but its type `Struct' has none
In the second argument of `sortBy', namely `(substructs xs)'
In the expression: sortBy (compare `on` fst) (substructs xs)

为什么不使用unzip功能。 如果我们定义一个辅助功能:

unSubStruct :: SubStruct -> (Int, Int)
unSubStruct (SubStruct p) = p

然后,可以将返回所需元素的函数编写为:

getMin :: Struct -> SubStruct
getMin (Struct l) = SubStruct (minimum xs, minimum ys)
  where
    (xs, ys) = unzip $ map unSubStruct l

请注意,这将遍历列表两次。 如果您定义自己的minimum版本对可以工作,则可以避免这种情况:

getMin :: Struct -> SubStruct
getMin (Struct l) =
    SubStruct $ foldr1 minPair $ map unSubStruct l
  where
    minPair (x0, y0) (x, y) = (min x0 x, min y0 y)

您有一个SubStruct列表,该列表与元组列表基本相同。

因此,仅使用通用功能的一种解决方案是:

result = SubStruct (min1, min2) where
    min1 = minimum (map fst . list)
    min2 = minimum (map snd . list)
    list = case substructs of
         Struct this -> map (\(SubStruct t) -> t) this

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM