例外:Prelude.head:空列表

时间:2015-01-03 00:38:21

标签: haskell empty-list

这是我对扩展功能的尝试:

expand :: FileContents -> FileContents -> FileContents  
expand textfile infofile  
  = concat (combine (fst (split separators textfile)) (expand' (snd (split separators textfile))   infofile "")   )  
    where  
      expand' [] _ stack = []  
      expand' (t:ts) info stack  
        |(head t) == '$' = (head (change t info )):expand' ts info stack  
        |otherwise = t: expand' ts info stack  
          where  
            change x y  
              = lookUp x (getKeywordDefs (snd (split ['\n'] y)))  

当我这样做时:

expand "Keywords (e.g. $x, $y, $z...) may appear anwhere, e.g. <$here>." "$x $a\n$y $b\n$z $c\n$here $this-is-one"

我得到了

 Exception: Prelude.head: empty list

但我想要

"Keywords (e.g. $a, $b, $c...) may appear anwhere, e.g. <$this-is-one>."

因为我应该

("Keywords (e.g. $x, $y, $z...) may appear anwhere, e.g. <$here>.",
   "$x $a\n$y $b\n$z $c\n$here $this-is-one")
    ==> "Keywords (e.g. $a, $b, $c...) may appear anwhere, e.g. <$this-is-one>."

ADDITION 我自己定义了分裂,即:

split :: [Char] -> String -> (String, [String])  
split separators ( x : wordsrest)  
      | elem x separators  = (x : listseparators,"" : word : listwords)  
      | otherwise          = (listseparators, ((x : word) : listwords))  
        where  
          (listseparators,    word : listwords) = split separators wordsrest  
split _ _ = ("" , [""])  
例如,

如果我输入

split " .," "A comma, then some words."

然后我会得到

(" , .",["A","comma","","then","some","words",""])

1 个答案:

答案 0 :(得分:1)

正如您所见in the docsplit不会将分隔符保留在它输出的块中,因此它们很可能是空的。

因此,在警卫中使用(head t) == '$'是不安全的,并且可能导致异常被提出。