【发布时间】:2017-10-09 20:22:31
【问题描述】:
我目前正在使用 Haskell 开发莫尔斯电码编码器。这是我第一次在 Haskell 工作,我发现很难以“功能性”的方式思考。到目前为止,我想出了这个:
module Formative1
(encode, decode, toTree, toTable)
where
import safe Lib
encode :: String -> [MorseUnit]
encode str = codeText(words str)
codeWord :: String -> [MorseUnit]
codeWord word = map codeSymbol word
codeText :: [String] -> [MorseUnit]
codeText list = map codeWord list
解释我的代码:
encode 是主要功能。它使用words 将句子分解为单词列表。 codeText 用于将函数 codeWord 应用于列表中的每个单词。 codeWord 然后maps 覆盖每个单词中的每个字符,并使用codeSymbol 找到MorseUnit。
我对这个解决方案有两个问题:
问题 1:由于[MorseUnit] 与[[MorseUnit]] 不匹配,每次运行时都会出错,我相信这是因为我使用了两次map,所以它在列表中列出。但是如果不使用map,我想不出另一种解决方案。
Issue2:摩尔斯电码规则规定,每个字母后面应该有一个“shortGap”,每个单词后面应该有一个“mediumGap”。我不知道如何在列表的每个元素之间插入任一字符串(我会在 map codeSymbol word 的每个元素之间插入 shortGap,所以 shortGap 在每个字母之间,我会在 map codeWord list 的每个元素之间插入 mediumGap,所以 mediumGaps在每个单词之间)。我也不明白我会在什么时候添加空白,因为我不想不小心将codeSymbol 应用于任何空白并替换它们。
任何解决方案都会有所帮助!谢谢。
【问题讨论】:
-
对于插入间隙,您可能需要
intersperse。对于类型错误,您可能只想使用concat将列表展平到位。在没有看到更多数据类型的情况下,这是我能提供的最好的帮助! -
@jkeuhlen 感谢您的回复。通过使用 concat,我已经能够摆脱 [[MorseUnit]] 问题。但是,无论我在哪里插入“intersperse”,都会遇到匹配类型和范围的问题。这是我的代码: encode :: String -> [MorseUnit] encode str = codeText (words str) codeWord :: String -> [MorseUnit] codeWord word = intersperse("shortGap" (concat(map codeSymbol word))) codeText :: [String] -> [MorseUnit] codeText list = intersperse("mediumGap" (concat(map codeWord list)))
标签: list haskell types syntax morse-code