Haskell:自定义数据类型的排序向量

时间:2019-02-08 02:22:47

标签: haskell

如何使用sortBy中的Data.Vector.Algorithms对自定义数据类型的向量进行排序,即:

data Person = Person 
  { name :: String
  , age  :: Int
  } deriving (Show, Eq)

p1,p2,p3 :: Person
p1 = Person "Alice"   30
p2 = Person "Bob"     20
p3 = Person "Charles" 10

personVec :: Vector Person
personVec = fromList [p2,p1,p3]

我想做类似的事情:

sortedByName :: Vector Person
sortedByName = modify (sortBy (comparing name)) personVec

sirtedByAage :: Vector Person
sortedByAge  = modify (sortBy (comparing age)) personVec

但不知道将什么作为sortBy的参数

1 个答案:

答案 0 :(得分:2)

提出问题

请包括一个MCVE,其中包括导入,编译指示,代码和错误。例如:

{-# LANGUAGE OverloadedLists #-}
import Data.Vector
import Data.Ord
import Data.Vector.Algorithms.Intro

data Person = Person.
  { name :: String
  , age  :: Int
  } deriving (Show, Eq)

p1,p2,p3 :: Person
p1 = Person "Alice"   30
p2 = Person "Bob"     20
p3 = Person "Charles" 10

personVec :: Vector Person
personVec = fromList [p2,p1,p3]

sortedByName :: Vector Person -> Vector Person
sortedByName = modify sortBy (comparing name) personVec

sortedByAge :: Vector Person -> Vector Person
sortedByAge  = modify sortBy (comparing age) personVec

通过ghci-8.4.3 $file加载时,会产生包括以下最后一项在内的错误:

so.hs:23:31: error:
    • Couldn't match expected type ‘Vector a1’
                  with actual type ‘Person -> Person -> Ordering’
    • Probable cause: ‘comparing’ is applied to too few arguments
      In the second argument of ‘modify’, namely ‘(comparing age)’
      In the expression: modify sortBy (comparing age) personVec
      In an equation for ‘sortedByAge’:
          sortedByAge = modify sortBy (comparing age) personVec
   |
23 | sortedByAge  = modify sortBy (comparing age) personVec
   |                               ^^^^^^^^^^^^^
Failed, no modules loaded.

Args的父母

modify函数有2个参数,但是由于缺少括号,您传递了3个参数:

sortedByAge = modify (sortBy (comparing age)) personVec

类型:这是矢量还是函数?

您的sortedByAge变量被命名为暗示它是一个向量,但是您提供的类型表明它是一个计算向量的函数。让我们更改该类型:

sortedByAge :: Vector Person

sortedByName也一样。

结果

*Main> sortedByName
[Person {name = "Alice", age = 30},Person {name = "Bob", age = 20},Person {name = "Charles", age = 10}]
*Main> sortedByAge
[Person {name = "Charles", age = 10},Person {name = "Bob", age = 20},Person {name = "Alice", age = 30}]