删除列表中的空白元素(方案)

时间:2014-07-24 19:32:35

标签: list scheme lisp

我有几个元素的列表,其中一些是有用的并且有文本,其中一些是"" (空/ null),其中一些是各种空格("","","")。

是否有内置函数来检查整个元素是否为空格? 为了清楚起见,我不想(" foo foo1 foo2")成为(" foofoo1foo2")。

由于

编辑:当我尝试实施Justin Ethier的解决方案时,我收到了这个错误。 错误:要应用的错误类型:""

我跑的代码是

;;;Predicate for checking if a string is not empty or full of whitespaces
(define (notwhitespace? str)
  (if (equal? str "") #F 
    (call-with-current-continuation
     (lambda (return)
      (for-each
       (lambda (c)
         (if (not (char-whitespace? c)) #T #F))
        (string->list str))
        #F)
      )
    )
)

我将此与过滤器结合使用以尝试从列表中删除元素。

 (define (notwhitespace? str)
  (if (equal? str "") (return #f)
  (every char-whitespace? (string->list str))
  )
)

我正在使用麻省理工学院计划

2 个答案:

答案 0 :(得分:0)

有一个内置函数char-whitespace?可用于确定单个字符是否为空白。然后,您可以将其包装在函数中以测试整个字符串,例如:

(call/cc
  (lambda (return)
    (for-each
      (lambda (c)
        (if (not (char-whitespace? c)) (return #t) #f))
      (string->list "  ")) ; Substitute your string var here
    #f))

或者更简洁:

(every char-whitespace? (string->list my-string))

您可以根据此功能创建一个功能,然后将其与filter一起使用,从列表中删除任何此类字符串。

答案 1 :(得分:-3)

我所知道的任何语言中都没有内置函数可以按照您的建议清理对象。您可以将列表对象传递给另一个具有相同类型的方法/函数。一些代码示例可能有助于提供更具体的答案,但这里有一个逻辑可能有助于清理列表对象:

function ListObject functionName(ListObject yourListObject)
{
    ListObject newListObject = new ListObject();
    foreach(var item in yourListObject)
    {
        if(!string.IsNullOrEmpty(item))
        {
            newListObject.Add(item);
        }
    }
    return newListObject;
}
相关问题