【问题标题】:problems with understanding types in haskell在haskell中理解类型的问题
【发布时间】:2013-01-28 13:08:08
【问题描述】:

大家好,我想获取一个单词列表并返回一个类似的列表,但是 每次出现连续单词时都会进行以下替换。

一个例子是you 并把它变成u

我得到了以下内容:

hep :: [Word] -> [Word]
type Word = String

现在给我的问题是我正在尝试使用大小写表达式,这样我就不必重复代码,但我收到以下错误

Couldn't match expected type `Char' with actual type `[Char]'
In the pattern: "You"
In a case alternative: "You" -> "u" : hep xs
In the expression: case a of { "You" -> "u" : hep xs }

来自以下代码

hep [] = []
hep [a:xs] = case a of 
    "You" -> "u":hep xs

谁能告诉我问题出在哪里?

编辑:

我添加了以下代码

hep [] = [[]]
hep (a:xs) = case a of 
    "you" -> "u":hep xs
    "are" -> "r":hep xs
    "your" -> "ur":hep xs
    "boyfriend" -> "bf":hep xs
    "girlfriend" -> "gf":hep xs
    "great" -> "gr8":hep xs
    a -> a:hep xs

现在我如何能够添加一个大小写,以便如果列表中包含 2 或 3 个特定单词的顺序,我可以将其转换为首字母缩略词?

["By","The","way"] = ["btw"]

【问题讨论】:

  • 这给了我与“You”完全相同的错误 -> 'u'
  • 对我来说很好用。我在返回列表的末尾得到了一个额外的“”,不确定这是不是有意的
  • 奇怪,现在它对我有用,哈哈。我将如何再添加 2 个案例,以便我可以比较三个单词并缩写它?示例:“By”、“The”、“way”会变成“btw”

标签: haskell types


【解决方案1】:

您正在尝试匹配字符串列表的列表,但 hep 的类型是 [Word] -> [Word],这与此相矛盾。错误消息指的是这个事实。

但我猜你真正想要的是这个?

hep [] = []
hep (a:xs) = case a of 
    "You" -> "u":hep xs
    a -> a:hep xs

【讨论】:

  • 谢谢,这对我帮助很大。没有注意到支架不见了。顺便说一句,当我添加额外的案例时,我得到了一个错误。我会编辑帖子,以便您更清楚地阅读。
【解决方案2】:

这样的?

"By" -> let (y:ys) = xs
        in if y=="The" && head ys=="Way"
              then "btw": hep (drop 2 xs)
              else a:hep xs

虽然我不想连续写 50 次。这个怎么样?

import Data.List
import Data.Maybe

hep [] = []
hep (a:xs) = case a of 
              "you" -> "u":hep xs
              "are" -> "r":hep xs
              "your" -> "ur":hep xs
              "boyfriend" -> "bf":hep xs
              "girlfriend" -> "gf":hep xs
              "great" -> "gr8":hep xs
              "by" -> matchPhrase 3
              "see" -> matchPhrase 2
              a -> a:hep xs
            where matchPhrase num = 
                    let found = lookup (concat $ take num (a:xs)) phrase_list
                    in case found of
                        Just _ -> fromJust found : hep (drop num (a:xs)) 
                        Nothing -> a:hep xs

phrase_list = [("bytheway", "btw"), ("seeyou","cu")]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-11
    相关资源
    最近更新 更多