Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

implement String(::Base.Generator) #57072

Open
StefanKarpinski opened this issue Jan 16, 2025 · 1 comment
Open

implement String(::Base.Generator) #57072

StefanKarpinski opened this issue Jan 16, 2025 · 1 comment
Labels
good first issue Indicates a good issue for first-time contributors to Julia help wanted Indicates that a maintainer wants help on an issue or pull request strings "Strings!"

Comments

@StefanKarpinski
Copy link
Member

I was hoping that this would work:

String(Iterators.map(c->c+1, "Hello, world"))

Instead it's a method error. We should allow the String constructor to take a generator argument.

@StefanKarpinski StefanKarpinski added good first issue Indicates a good issue for first-time contributors to Julia help wanted Indicates that a maintainer wants help on an issue or pull request strings "Strings!" labels Jan 16, 2025
@ararslan
Copy link
Member

Perhaps a method that consumes general iterators would be worthwhile, e.g.

🍝(x, ::Union{HasLength,HasShape}) = String(copyto!(StringMemory(length(x)), x))
🍝(x, ::IsInfinite) = throw(MethodError(String, (x,)))
function 🍝(x, ::SizeUnknown)
    io = IOBuffer()
    for c in x
        print(io, convert(AbstractChar, c))
    end
    return String(take!(io))
end

String(itr) = 🍝(itr, IteratorSize(itr))

That would allow supporting things like String(Iterators.take("Hello, world", 5)) as well.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
good first issue Indicates a good issue for first-time contributors to Julia help wanted Indicates that a maintainer wants help on an issue or pull request strings "Strings!"
Projects
None yet
Development

No branches or pull requests

2 participants