簡體   English   中英

對字符串使用haskell map函數

[英]Using the haskell map function with a string

我正在嘗試在haskell中使用map函數

我有這個:

lexi :: String -> [[String]]
lexi x = map (words.lines) x

我希望能夠將字符串放入x,因此可以像這樣運行

lexi ("string here")

但是得到錯誤

Couldn't match type ‘[Char]’ with ‘Char’
Expected type: String -> String
  Actual type: String -> [String]
In the second argument of ‘(.)’, namely ‘lines’
In the first argument of ‘map’, namely ‘(words . lines)’

Couldn't match type ‘Char’ with ‘[Char]’
Expected type: [String]
  Actual type: String
In the second argument of ‘map’, namely ‘x’
In the expression: map (words . lines) x

我知道如果我使用

lexi = map (words.lines) 

當我運行lexi ("string here") ,它工作正常,但需要稍后使用的變量

可以請一些人解釋為什么它不起作用以及如何解決?

謝謝 :)

該答案是該問題的舊版本

因此,讓我們弄清楚這一點(請始終添加您正在談論的所有函數的類型簽名!)

function :: Char -> [String]

好吧,然后map function的類型為[Char] -> [[String]] ,即String -> [[String]] 但是您希望結果僅是[String] ,而不是三重嵌套的列表。 您可能希望將兩個級別的列表一起加入; 在一般用於列表接合目的的功能是concat (或更一般地, joinControl.Monad模塊)。 在這種情況下,您有兩個不同的選擇:

  • 將每個對function調用的結果結合起來。 即,您可以映射join . function而不是單獨使用映射function join . function join . function ,其類型為Char -> String 具有所需類型String -> [String]映射。

     lexi = map $ join . function 
  • 加入映射的最終結果,即lexi = join . map function lexi = join . map function 映射和聯接結果的這種組合實際上是一個極為常見的任務,它具有一個特殊的運算符:monadic bind!

     lexi x = x >>= function 

新版本

所以我們知道

words, lines :: String -> [String]

這樣的words . lines words . lines無法工作,因為您正嘗試將字符串列表提供給僅接受單個字符串的函數。 當然,您可以做的是在結果放置映射 words ,即map words . lines map words . lines 實際上,它具有正確的簽名,並且可能會按照您的要求進行操作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM