在haskell中找到拼字游戏单词的分数

时间:2014-04-24 08:55:14

标签: haskell

我正在用相应的分数映射一个字母

dict = fromList([("A",1), ("B",3), ("C", 3), ("E", 1), ("D", 2), ("G", 2), ("F", 4), ("I", 1), ("H", 4), ("K", 5), ("J", 8), ("M", 3), ("L", 1), ("O", 1), ("N", 1), ("Q", 10), ("P", 3), ("S", 1), ("R", 1), ("U", 1), ("T", 1), ("W", 4), ("V", 4), ("Y", 4), ("X", 8), ("Z", 10)])

如果主要向该函数发送一个单词,该函数应该返回与该单词和字母中的字母相关的分数。

EX: - 主要: - APPLE 功能应该返回: - 9

(A Score)1+(P Score)3 +(P Score)3 + (L Score) 1+(E Score)1 = 9 

2 个答案:

答案 0 :(得分:4)

您可以使用lookup创建一个将键映射到值的函数:

mapper :: Eq k => [(k, v)] -> k -> v
mapper dict k = case lookup k dict of Nothing  -> undefined
                                      (Just v) -> v

scrabble :: Char -> Int
scrabble = mapper [ ('A', 1)
                  , ('B', 3)
                  , ('C', 3)
                  , ('E', 1)
                  , ('D', 2)
                  , ('G', 2)
                  , ('F', 4)
                  , ('I', 1)
                  , ('H', 4)
                  , ('K', 5)
                  , ('J', 8)
                  , ('M', 3)
                  , ('L', 1)
                  , ('O', 1)
                  , ('N', 1)
                  , ('Q', 10)
                  , ('P', 3)
                  , ('S', 1)
                  , ('R', 1)
                  , ('U', 1)
                  , ('T', 1)
                  , ('W', 4)
                  , ('V', 4)
                  , ('Y', 4)
                  , ('X', 8)
                  , ('Z', 10)
                  ]

现在你需要做的就是创建一个函数,它接受一个字符串并返回它的分数:

score :: String -> Int
score = sum . map scrabble

main = print $ score "APPLE"

就是这样。

修改:查找失败时,在undefined中返回mapper没有任何问题。如果您需要错误处理,则可以将mapper定义为flip lookup,而现在scrabble类型为Char -> Maybe Int

考虑如何使用模式匹配编写scrabble

scrabble :: Char -> Int
scrabble 'A' = 1
scrabble 'B' = 3
scrabble 'C' = 3
scrabble 'D' = 2
scrabble 'E' = 1
scrabble 'F' = 4
scrabble 'G' = 2
scrabble 'H' = 4
scrabble 'I' = 1
scrabble 'J' = 8
scrabble 'K' = 5
scrabble 'L' = 1
scrabble 'M' = 3
scrabble 'N' = 1
scrabble 'O' = 1
scrabble 'P' = 3
scrabble 'Q' = 10
scrabble 'R' = 1
scrabble 'S' = 1
scrabble 'T' = 1
scrabble 'U' = 1
scrabble 'V' = 4
scrabble 'W' = 4
scrabble 'X' = 8
scrabble 'Y' = 4
scrabble 'Z' = 10

如果模式匹配失败,那么无论如何最终都会得到一个底值。如果您知道模式匹配永远不会失败,那么这不是问题。如果您确实需要处理故障,那么只需使用我上面提到的flip lookup

答案 1 :(得分:0)

main = print $ calWordScore "APPLE"

calcWordScore :: String -> Int
calcWordScore word = sum $ map calcLetterScore word

calcLetterScore :: Char -> Int
calcLetterScore ch = Map.fromList([('A',1), ('B',3), ('C', 3), ('E', 1), ('D', 2), ('G', 2), ('F', 4), ('I', 1), ('H', 4), ('K', 5), ('J', 8), ('M', 3), ('L', 1), ('O', 1), ('N', 1), ('Q', 10), ('P', 3), ('S', 1), ('R', 1), ('U', 1), ('T', 1), ('W', 4), ('V', 4), ('Y', 4), ('X', 8), ('Z', 10)]) Map.! ch

你需要     导入限定的Data.Map.Lazy作为Map