![](/img/trans.png)
[英]Haskell: add the second elements of 2 tuples if their first elements are equal, in a list of tuples?
[英]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 elements
剛接觸 Haskell。 所以我做的第一個函數sort_by
使用快速排序對 a 類型的列表進行排序 - 工作正常。
下一個函數 compare by 接受一個比較器類型(定義如下)和一個函數並返回一個比較器 - 所以GT
, EQ
等。這兩個函數我必須只使用函數定義。 現在的問題 - 我應該使用這兩個函數來使用柯里化定義基於標題的函數,但我不知道我的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)] = ??
面對這些問題時,查看類型並從那里開始工作會很有幫助。
您需要使用sort_by
和compare_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 (a, b) -> 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 的類型化孔功能。 如果您編譯帶有漏洞的代碼,GHC 會告訴您需要哪種類型的表達式,並建議可以填充漏洞的可能綁定(例如函數和參數)。
作為一個側面說明, compare_by
功能的專業化和翻轉版本on
從Data.Function
:
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.