How do I convert a string to a list in Io?

牧云@^-^@ 提交于 2019-12-10 02:56:28

问题


For example, I'd like to turn "hello" into list(104, 101, 108, 108, 111) or list("h", "e", "l", "l", "o")

So far I've created an empty list, used foreach and appended every item to the list myself, but that's not really a concise way to do it.


回答1:


My own suggestion:

Sequence asList := method(
  result := list()
  self foreach(x,
    result append(x)
  )
)

Haven't tested it performance-wise but avoiding the regexp should account for something.




回答2:


Another nicely concise but still unfortunately slower than the foreach solution is:

Sequence asList := method (
    Range 0 to(self size - 1) map (v, self at(v) asCharacter)
)



回答3:


One way would be to use Regex addon:

#!/usr/bin/env io

Regex

myList := "hello" allMatchesOfRegex(".") map (at(0))

But I'm sure there must be other (and perhaps even better!) ways.


Update - re: my comment in question. It would be nice to have something built into Sequence object. For eg:

Sequence asList := method (
    Regex
    self allMatchesOfRegex(".") map (at(0))
)

# now its just
myList := "hello" asList



回答4:


I have Io Programming Language, v. 20110905 and method asList is defined by default, so you can use it without any new definitions. Then you can get char codes with map method.

Io 20110905
Io> a := "Hello World"
==> Hello World
Io> a asList
==> list(H, e, l, l, o,  , W, o, r, l, d)
Io> a asList map(at(0))
==> list(72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100)


来源:https://stackoverflow.com/questions/4255123/how-do-i-convert-a-string-to-a-list-in-io

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!