[ Skill ] 如何 flatten 一个 list

https://www.cnblogs.com/yeungchie/

  • code
procedure(ycFlattenList(listin @optional keep(nil))
    prog((output havep)
        foreach(arg listin
            cond(
                (listp(arg)
                    case(keep
                        (nil
                            output = append(output ycFlattenList(arg keep))
                        )
                        (t
                            havep = nil
                            foreach(x arg
                                if(listp(x) havep = t)
                            )
                            if(havep
                                output = append(output ycFlattenList(arg keep))
                                output = append1(output arg)
                            )
                        )
                    )
                )
                (t
                    output = append1(output arg)
                )
            );cond
        );foreach
        return(output)
    );prog
);ycFlattenList
  • describe
  1. 输入一个list,返回一个被Flatten的list。
  2. 可以指定第二参数keep为t,用来保留最后一级list;keep默认为nil。(这是我在某个特殊场景下的需求)
  • example
ycFlattenList('((1 2) 3 (4 (5 6))))
=>(1 2 3 4 5 6)
ycFlattenList('((1 2) 3 (4 (5 6))) t)
=>((1 2) 3 4 (5 6))
原文地址:https://www.cnblogs.com/yeungchie/p/13020531.html