Instantly share code, notes, and snippets.

# menduz/transform.dwl

Created October 11, 2017 16:48
DataWeave prime number generator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
 %dw 2.0 output application/json import some from dw::core::Arrays fun isPrime(num: Number): Boolean = do { // try primes <= 16 if (num <= 16) (num == 2) or (num == 3) or (num == 5) or (num == 7) or (num == 11) or (num == 13) else if ( // cull multiples of 2, 3, 5 or 7 ((num mod 2) == 0) or ((num mod 3) == 0) or ((num mod 5) == 0) or ((num mod 7) == 0) ) false // cull square numbers ending in 1, 3, 7 or 9 else if( sequence(1) map (\$ * 10) takeUntil (\$ * \$) < num some ( (num mod (\$ + 1)) == 0 or (num mod (\$ + 3)) == 0 or (num mod (\$ + 7)) == 0 or (num mod (\$ + 9)) == 0 ) ) false else true } fun takeUntil(list: Array, condition: (T, Number) -> Boolean): Array = do { fun until(list: Array, condition: (T, Number) -> Boolean, startIndex: Number): Array = list match { case [] -> [] case [head ~ tail] -> if(condition(head, startIndex)) [head ~ until(tail, condition, startIndex + 1)] else [head] } --- until(list, condition, 0) } fun sequence(start = 0) = [start ~ sequence(start + 1)] fun primeGenerator() = (sequence(0) filter isPrime(\$)) fun primes(qty: Number, start: Number = 0) = primeGenerator()[(start) to (start+qty-1)] --- // primeGenerator() //999th prime number primes(100)

### Allizwell1 commented Dec 13, 2021

this code is not working beyond 6... if you pass more than 6 to prime it wont take please solve and reply..