這個表達式:新手上sort.words
sort words "fire water earth fire"
---給出了這樣的錯誤---
Couldn't match expected type `[a]'
against inferred type `GHC.Base.String -> [GHC.Base.String]'
有人能向我解釋,這到底是怎麼回事,如何優雅地表達排序。話?
這個表達式:新手上sort.words
sort words "fire water earth fire"
---給出了這樣的錯誤---
Couldn't match expected type `[a]'
against inferred type `GHC.Base.String -> [GHC.Base.String]'
有人能向我解釋,這到底是怎麼回事,如何優雅地表達排序。話?
你想這樣的:
sort (words "fire water earth fire")
當你做
sort words "fire water earth fire"
它實際上做
(sort words) "fire water earth fire"
sort
預計列表([a]
),但你不是給它words
,這是一個函數接受一個字符串並返回s的列表(String -> [String]
),因此錯誤信息(它不能把String -> [String]
作爲任何東西的列表)。
你也可以這樣做:
sort $ words "fire water earth fire"
這相當於第一版本,看起來更整潔。
函數應用程序是從左邊關聯的,因此解析爲(sort words) "fire water earth fire"
。不用說,排序功能words
不會工作得很好!因此,錯誤消息告訴您,sort
需要[a]
(即列表)類型的參數,但您已將其應用於某種類型的String -> [String]
,即words
。
你想要麼sort (words "fire water earth fire")
,要麼使用更常見的成語sort $ words "fire water earth fire"
。 ($)
運算符只是函數應用程序,但它具有非常低的右關聯優先級,所以它經常用於像這樣的表達式中以避免寫出括號。
哇,答案就在我眼前!感謝:D – 2012-01-13 22:30:22