【问题标题】:Haskell - I have a question split into 3 parts - using the first 2 functions make a function that sorts a list of tuples on the first elementsHaskell - 我有一个问题分为 3 个部分 - 使用前 2 个函数创建一个函数,对第一个元素的元组列表进行排序
【发布时间】:2021-12-20 07:31:26
【问题描述】:

haskell 新手。所以我创建的第一个函数 sort_by 使用快速排序对 a 类型的列表进行排序 - 工作正常。

下一个函数 compare 接受一个比较器类型(定义如下)和一个函数并返回一个比较器 - 所以GTEQ 等。这两个函数我都必须只使用函数定义。现在的问题 - 我应该使用这两个函数来定义一个基于标题的函数,但我不知道我的 compare_By 函数应该如何帮助创建这样的函数?

非常感谢任何帮助。谢谢。

import GHC.Show (Show)
type Comparator a   = a -> a -> Ordering
type Tokeniser a    = String -> [a]
type Translator a b = a -> Maybe b

data English = E String deriving (Show)
data French  = F String deriving (Show)
data German  = G String deriving (Show)


sort_by :: Comparator a -> [a] -> [a]
sort_by o as = qs as []
    where qs [] as' = as'
          qs (a:as) as' = qs les $ a : qs gts as'
            where les = [a' | a' <- as, a  `o` a' == GT] 
                  gts = [a' | a' <- as, a `o` a' /= GT]

compare_by :: (b -> a) -> Comparator a -> Comparator b
compare_by f o a b = o (f a) (f b)

sort_by_fst :: Comparator a -> [(a,b)] ->[(a,b)]
sort_by_fst f [(a,b)] = ??

【问题讨论】:

  • 如果你想把Comparator a变成Comparator (a,b),你需要把什么类型的函数传给compare_by,你能想到这样的函数吗?
  • 在不相关的说明中,使用[(a,b)] 作为模式意味着您的函数将仅适用于单元素列表。
  • 有mb

标签: haskell functional-programming


【解决方案1】:

当遇到这些问题时,查看类型并从那里开始工作会很有帮助。

您需要使用sort_bycompare_by 来创建sort_by_fst。显然,我们需要sort_by 来对列表进行排序,所以让我们看看它的类型:

sort_by :: Comparator a -> [a] -> [a]

太好了,让我们用它来对列表进行排序:

sort_by_fst f xs = sort_by _comparator xs

再次查看sort_by 的类型,我们可以看到我们需要一个Comparator (a, b) 来对xs :: [(a, b)] 进行排序。但是我们只有一个f :: Comparator a,所以使用compare_by 得到一个Comparator (a, b)

compare_by :: (b -> a) -> Comparator a -> Comparator b
-- Specialising to the types we need (substituting b = (a, b)):
compare_by :: ((a, b) -> a) -> Comparator a -> Comparator (a, b)

除了Comparator a,我们还需要(a, b) -&gt; a:一个获取元组第一个元素的函数。 fst 正是这样做的:

sort_by_fst f xs = sort_by (compare_by fst f) xs

这也可以写得更简洁

sort_by_fst = sort_by . compare_by fst

顺便说一下,_name(例如_comparator)的语法是GHC’s typed holes feature。如果你编译有漏洞的代码,GHC 会告诉你需要什么类型的表达式,并建议可能的绑定(例如函数和参数)来填补漏洞。


附带说明一下,compare_by 函数是来自Data.Functionon 的专用翻转版本:

on :: (b -> b -> c) -> (a -> b) -> a -> a -> c 

sort_by_fst 因此可以这样实现:

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

sort_by_fst :: Comparator a -> [(a, b)] -> [(a, b)]
sort_by_fst f = sortBy (f `on` fst)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-08-18
    • 1970-01-01
    • 2012-02-10
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 2019-11-25
    • 2017-02-03
    相关资源
    最近更新 更多