【发布时间】:2021-11-20 12:09:47
【问题描述】:
我正在尝试制作一个程序,它接收一个字母并将该字母转换为 摩尔斯电码。
给出了莫尔斯表,还有charToCode :: [(Char, String)] -> Char -> String
我还必须使用 lookup 和 fromJust 表单 Data.Maybe 来完成这项工作。编译后我收到以下错误:
Couldn't match expected type [Maybe Char]
with actual type Maybe String
* In the second argument of 'map', namely '(lookup a f)'
In the expression: map (fromJust) (lookup a f)
In an equation for 'charToCode':
charToCode f a = map (fromJust) (lookup a f)
我必须使用 Prelude 中的地图。到目前为止,这是我的代码:
morseTab :: [(Char, String)]
morseTab = [('A', ".-"), ('B', "-..."), ('C', "-.-."), ('D', "-.."), ('E', "."), ('F', "..-."), ('G', "--."), ('H', "...."),('I', ".."), ('J', ".---"), ('K', "-.-"), ('L', ".-.."), ('M', "--"), ('N', "-."), ('O', "---"), ('P', ".--."), ('Q', "--.-"), ('R', ".-."), ('S', "..."), ('T', "-"), ('U', "..-"), ('V', "...-"), ('W', ".--"), ('X', "-..-"), ('Y', "-.--"), ('Z', "--..")]
charToCode :: [(Char, String)] -> Char -> String
charToCode f a = map (fromJust) (lookup a f)
morseTab 是一个给定的函数,我也无法对其进行更改。
【问题讨论】:
-
你不应该使用
map。lookup a f的结果是Maybe String,而不是Maybe Strings 的列表。 -
@WillemVanOnsem 有没有办法让我的 Maybe String 变成一个只包含一个 Maybe String 元素的列表?然后将其传递给地图
标签: haskell higher-order-functions maybe