所以我有一个自定义数据类型,让我们调用它Struct
,定义如下:
data Struct = Struct [SubStruct] deriving (Read, Show)
data SubStruct = SubStruct (Int, Int) deriving (Read, Show)
Run Code Online (Sandbox Code Playgroud)
我需要做的是遍历所有元素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)
Run Code Online (Sandbox Code Playgroud)
但我得到这个错误:
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)
Run Code Online (Sandbox Code Playgroud)
为什么不使用该unzip
功能.如果我们定义一个辅助函数:
unSubStruct :: SubStruct -> (Int, Int)
unSubStruct (SubStruct p) = p
Run Code Online (Sandbox Code Playgroud)
然后返回所需元素的函数可以写为:
getMin :: Struct -> SubStruct
getMin (Struct l) = SubStruct (minimum xs, minimum ys)
where
(xs, ys) = unzip $ map unSubStruct l
Run Code Online (Sandbox Code Playgroud)
请注意,这将遍历列表两次.如果您定义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)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
327 次 |
最近记录: |