how to make HTML from a list in scheme, racket

后端 未结 1 447
借酒劲吻你
借酒劲吻你 2021-01-22 11:31

This is a very long question ... I am new and joined, so please don\'t attack me. Apologies for my bad communications in English. I have some defintions:

An HTML(H) is on

相关标签:
1条回答
  • 2021-01-22 12:33

    You have the right idea, but still - there are three main issues with your proposed solution:

    • The output will be a string, not a list, so we must append strings in the recursive steps and return strings in the base cases.
    • Symbols must be explicitly converted to strings if we want to concatenate them with other strings.
    • And last but not least: you're missing a couple of base cases, and these are essential for writing a correct solution: what should happen if the given html is an empty list? What if the first element in a list is not a symbol, but another list?

    This will work, take a careful look at the things that changed:

    (define (html->string html)
      (cond [(empty? html) ""]
            [(string? html) html]
            [(not (symbol? (first html)))
             (html->string (first html))]
            [else (string-append
                   "<" (symbol->string (first html)) ">"
                   (change-tag (rest html))
                   "</" (symbol->string (first html)) ">")]))
    
    (define (change-tag lst)
      (cond [(empty? lst) ""]
            [else (string-append
                   (html->string (first lst))
                   (html->string (rest lst)))]))
    

    It works as expected:

    (define html
      (list 'html
            (list 'head
                  (list 'title "Hi"))
            (list 'body
                  (list 'h1 "Welcome")
                  "Text")))
    
    (html->string html)
    => "<html><head><title>Hi</title></head><body><h1>Welcome</h1>Text</body></html>"
    
    0 讨论(0)
提交回复
热议问题