เขียน replicateM ด้วย C#

wk
wk
Jul 30, 2017 · 1 min read

Haskell มีฟังก์ชัน replicateM สามารถใช้สร้าง combination ของ input ตามความยาวที่ต้องการ เช่น ถ้าต้องการสร้าง combination ของ 1 และ 2 ให้มีขนาด n = 3 สามารถใช้ฟังก์ชัน replicateM ดังนี้

λ> import Control.Monad
λ> replicateM 3 [1,2]
[[1,1,1],[1,1,2],[1,2,1],[1,2,2],[2,1,1],[2,1,2],[2,2,1],[2,2,2]]

ผลลัพธ์ของฟังก์จะคล้ายกับการเขียน for loop 3 ชั้น แล้วนำ element ของแต่ละ loop มารวมกัน

ใน C# ไม่มีฟังก์ชันที่ทำงานเหมือนกับ replicateM แต่สามารถเขียนขึ้นเองโดยใช้ ฟังก์ชัน recursive ดังนี้

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade