September 16, 2018 Re: array to string functional? | ||||
---|---|---|---|---|
| ||||
Posted in reply to Paul Backus | > Can you post a complete, runnable example that illustrates your problem?
Strange as it is, now it works here too... - I don't know, what went wrong yesterday. Thanks anyway. :-)
|
September 16, 2018 Re: array to string functional? | ||||
---|---|---|---|---|
| ||||
Posted in reply to SrMordred | On Friday, 14 September 2018 at 20:43:45 UTC, SrMordred wrote: > On Friday, 14 September 2018 at 19:44:37 UTC, berni wrote: >> a) I've got an int[] which contains only 0 und 1. And I want to end with a string, containing 0 and 1. So [1,1,0,1,0,1] should become "110101". Of course I can do this with a loop and ~. But I think it should be doable with functional style, which is something I would like to understand better. Can anyone help me here? (I think a.map!(a=>to!char(a+'0')) does the trick, but is this good style or is there a better way?) Yes, that's fine. That gives you a range; if you want an array, call array() with that expression. Also, since you know the addition won't overflow, you can substitute the to!char call with a cast (arr.map!(c => cast(char)(c + '0')).array). Another option is to index a string literal: arr.map!(c => "01"[c]).array > auto a = [1,0,1,1,1,0,1,0,1,1,1,1,0]; > a.map!(to!string) > .join("") > .chunks(4) > .map!(to!string) //donĀ“t know why the chunks are not already strings at this point ;/ > .writeln; That's needlessly complicated and inefficient; this will allocate one string per array element. If you don't need the result to be actual arrays, this works: auto res = [1,0,1,1,1,0,1,0,1,1,1,1,0] .map!(c => "01"[c]) .chunks(4); assert(equal!equal(res, ["1011","1010","1111","0"])); If you need a real array of arrays: auto arr = res .map!array .array; assert(arr == ["1011","1010","1111","0"]); |
Copyright © 1999-2021 by the D Language Foundation