我最近接到了一项我已经完成的任务,目前我需要一些帮助。
我需要实现的第一个功能是lookUp,split,combine和keyWordDefs。
然后我必须实现一个函数expand :: FileContents - > FileContents - > FileContents获取文本文件和信息文件的内容,并使用上述函数组合它们以构建表示输出文件的字符串。
到目前为止,这是我的代码:
module MP where
import System.Environment
type FileContents = String
type Keyword = String
type KeywordValue = String
type KeywordDefs = [(Keyword, KeywordValue)]
separators :: String
separators
= " \n\t.,:;!\"\'()<>/\\"
lookUp :: String -> [(String, a)] -> [a]
-- Given a search string and a list of string/item pairs, returns
-- the list of items whose associated string matches the search string.
lookUp x y = [a|(b,a) <- y, x==b]
split :: String -> String -> (String, [String])
-- Breaks up a string.
split as [] = ("",[""])
split as (b:bs)
| elem b as = (b:xs,"":y:ys)
| otherwise = (xs, (b:y):ys)
where
(xs,y:ys) = split as bs
combine :: [Char] -> [String] -> [String]
-- Combines the components of a string from its constituent separator
-- characters and words, as generated by a call to split.
combine [] y = y
combine (x:xs)(y:ys) = y : [x] : combine xs ys
getKeywordDefs :: [String] -> KeywordDefs
-- Takes the contents of an information file in the form of a list
-- of lines and which returns a list of keyword/definition pairs.
getKeywordDefs [] = []
getKeywordDefs (x:xs) = (keyword, concat defs) : getKeywordDefs xs
where
(_, (keyword : def)) = split " " x
defs = combine spaces def
spaces = [ ' ' | s <- [2..length def]]
expand :: FileContents -> FileContents -> FileContents
扩展功能的一个例子是:
expand "The capital of $1 is $2" "$1 Peru\n$2 Lima."
"The capital of Peru is Lima."
我认为如果在输入字符串中有一个“$”,那么第一次查找(使用函数lookUp),然后拆分单词,然后用第二个输入替换以“$”开头的单词字符串,然后再将它们组合在一起?实际上我真的很困惑,我想知道这里是否有人了解函数扩展是如何工作的。
欢迎任何帮助:)
答案 0 :(得分:1)
您的展开功能应如下所示:
-- It's probably better to change the type signature a little bit
-- because we're not returning the contents of a file, we're returning a string.
expand :: FileContents -> FileContents -> String
expand fc1 fc2 = let
keywordDefs = getKeywordDefs fc2
in replaceSymbols fc1 keywordDefs
然后你需要一个名为replaceSymbols的函数,它会在看到$ X时拆分fc1,然后用$ X代替在keywordDefs中查找$ X的结果。
replaceSymbols :: FileContents -> KeywordDefs -> String
如果您仍需要帮助,请继续执行该功能并回复此答案:)。