Ad
Code
Diff
  • module Sum (Sum.sum) where
    
    import Control.Monad.State (State,execState,put, get)
    import Data.Foldable (for_)
    
    sum :: [Int] -> Int
    sum xs = execState (for_ xs add) 0 where
      add :: Int -> State Int ()
      add x = do
        -- modify (+x)
        y <- get
        put (y + x)
        return ()
    • module Sum (Sum.sum) where
    • import Control.Monad.State (State,execState)
    • import Control.Monad.State (State,execState,put, get)
    • import Data.Foldable (for_)
    • sum :: [Int] -> Int
    • sum xs = execState (for_ xs add) 0 where
    • add :: Int -> State Int ()
    • add x = do
    • -- modify (+x)
    • y <- get
    • put (y + x)
    • return ()
Code
Diff
  • module Sum (Sum.sum) where
    
    import Prelude hiding (sum)
    
    sum :: [Word] -> Word
    sum xs = if xs == [] then 0 else foldr1 (+) xs
    • module Sum (Sum.sum) where
    • import Prelude hiding (sum)
    • sum :: [Word] -> Word
    • sum [] = 0
    • sum xs = foldr1 (+) xs
    • sum xs = if xs == [] then 0 else foldr1 (+) xs

Story

Johny is a moderator of a community of programmers from around the world. He has a website where users can ask programming questions. Unfortunately, new users quite often do not follow common netiquette and post large chunks of code without proper formatting, what makes Johny's life difficult: he has to ask many follow-up questions, and manually fix formatting of posts. Johny wants to improve the system so it detects missing code blocks in questions which are about to be posted, so it could notify users and ask them to improve their question.

Task

Create a function which accepts content of a post which is about to be submitted by a user. The function should return information about unformatted code blocks in the post.

  • The function should not detect formatted code blocks. The system uses Markdown formatting, and minimal requirement is to recognize code blocks surrounded with three backticks, and an optional language tag.
  • The function should return a falsy value if a post contains no unformatted code blocks.
  • Minimum version: the function should return a truthy value if a post contains unformatted code blocks.
  • Ideal version: the function returns one { startpos, endpos } for every detected unformatted code block.
  • Bonus points if the function returns also a content of the post after fixing it and adding missing markup.
  • False negatives are preferred over false positives. It's better to let some posts slip through than nag users without a reason.
  • The function should not be targeted at any specific programming language. Most users ask questions about JavaScript and Python code, so it would be nice if at least these two were supported, but the more the better.
  • Code should be clean, reviewable, and production ready.
  • Bonus points: special kudos goes to functions which are additionally able to detect missing markup of inline code spans.

Disclaimer

This is a Codewars kumite. There's no points for this, tests are only examples, and requirements are not set in stone. Feel free to fork and introduce any variation you feel is necessary, comment, add tests, discuss requirements.

The goal of the kumite is to trick smart people into giving me an implementation of a function which I would later use in a user script and prototype a functionality I would like to suggest to be implemented directly in Codewars.

function findCodeBlocks(text) {
  return text.includes("{")
}
import org.scalatest._

import org.scalatest.Reporter
import org.scalatest.events._

import java.io.{StringWriter, PrintWriter}

// http://doc.scalatest.org/3.0.0/index.html#org.scalatest.Reporter
class CodewarsReporter extends Reporter {
  override def apply(event: Event): Unit = event match {
    case s: SuiteStarting if s.suiteName != "DiscoverySuite" =>
      println(s"\n<DESCRIBE::>${s.suiteName}")

    case s: SuiteCompleted if s.suiteName != "DiscoverySuite" =>
      println(s"\n<COMPLETEDIN::>${durationString(s.duration)}")

    case s: SuiteAborted =>
      println(s"\n<ERROR::>Test Suite Aborted<:LF:>${replaceLF(s.message)}")
      s.throwable foreach showStackTrace
      println(s"\n<COMPLETEDIN::>${durationString(s.duration)}")

    case t: TestStarting =>
      println(s"\n<IT::>${t.testName}")

    case t: TestSucceeded =>
      println("\n<PASSED::>Test Passed")
      println(s"\n<COMPLETEDIN::>${durationString(t.duration)}")

    case t: TestFailed =>
      println(s"\n<FAILED::>Test Failed<:LF:>${replaceLF(t.message)}")
      t.throwable foreach showStackTrace
      println(s"\n<COMPLETEDIN::>${durationString(t.duration)}")

    case t: TestCanceled =>
      println(s"\n<FAILED::>Test Cancelled<:LF:>${replaceLF(t.message)}")
      t.throwable foreach showStackTrace
      println(s"\n<COMPLETEDIN::>${durationString(t.duration)}")

    case _: TestIgnored =>
      println(s"\n<LOG::>Test Ignored")
      println(s"\n<COMPLETEDIN::>")

    case _: TestPending =>
      println(s"\n<LOG::>Test Pending")
      println(s"\n<COMPLETEDIN::>")


    case _: DiscoveryStarting => ()
    case _: DiscoveryCompleted => ()

    case _: RunStarting => ()
    case _: RunStopped => ()
    case t: RunAborted =>
      println(s"\n<ERROR::>${replaceLF(t.message)}")
      t.throwable foreach showStackTrace
      println(s"\n<COMPLETEDIN::>")

    case _: RunCompleted => ()

    case _: ScopeOpened => ()
    case _: ScopeClosed => ()
    case _: ScopePending => ()

    // contained in recordedEvents?
    case _: InfoProvided => ()
    case _: MarkupProvided => ()
    case _: AlertProvided => ()
    case _: NoteProvided => ()

    case _ => ()
  }

  private def showStackTrace(throwable: Throwable): Unit = {
    val sw = new StringWriter
    throwable.printStackTrace(new PrintWriter(sw))
    println(s"<LOG::-Stack Trace>${sw.toString.replaceAll("\n", "<:LF:>")}")
  }

  private def durationString(d: Option[Long]) = d map { _.toString } getOrElse ""
  private def replaceLF(s: String) = s.replaceAll("\n", "<:LF:>")
}
class HobovskysReporter extends Reporter {
  override def apply(event: Event): Unit = event match {
    case s: SuiteStarting if s.suiteName != "DiscoverySuite" =>
      println(s"\n<DESCRIBE::>${s.suiteName}")

    case s: SuiteCompleted if s.suiteName != "DiscoverySuite" =>
      println(s"\n<COMPLETEDIN::>${durationString(s.duration)}")

    case s: SuiteAborted =>
      println(s"\n<ERROR::>Test Suite Aborted<:LF:>${replaceLF(s.message)}")
      s.throwable foreach showStackTrace
      println(s"\n<COMPLETEDIN::>${durationString(s.duration)}")

    case t: TestStarting =>
      println(s"\n<IT::>${t.testName}")

    case t: TestSucceeded =>
      println("\n<PASSED::>Test Passed X")
      println(s"\n<COMPLETEDIN::>${durationString(t.duration)}")

    case t: TestFailed =>
      println(s"\n<FAILED::>Test Failed<:LF:>${replaceLF(t.message)}")
      t.throwable foreach showStackTrace
      println(s"\n<COMPLETEDIN::>${durationString(t.duration)}")

    case t: TestCanceled =>
      println(s"\n<FAILED::>Test Cancelled<:LF:>${replaceLF(t.message)}")
      t.throwable foreach showStackTrace
      println(s"\n<COMPLETEDIN::>${durationString(t.duration)}")

    case _: TestIgnored =>
      println(s"\n<LOG::>Test Ignored")
      println(s"\n<COMPLETEDIN::>")

    case _: TestPending =>
      println(s"\n<LOG::>Test Pending")
      println(s"\n<COMPLETEDIN::>")


    case _: DiscoveryStarting => ()
    case _: DiscoveryCompleted => ()

    case _: RunStarting => ()
    case _: RunStopped => ()
    case t: RunAborted =>
      println(s"\n<ERROR::>${replaceLF(t.message)}")
      t.throwable foreach showStackTrace
      println(s"\n<COMPLETEDIN::>")

    case _: RunCompleted => ()

    case _: ScopeOpened => ()
    case _: ScopeClosed => ()
    case _: ScopePending => ()

    // contained in recordedEvents?
    case _: InfoProvided => ()
    case _: MarkupProvided => ()
    case _: AlertProvided => ()
    case _: NoteProvided => ()

    case _ => ()
  }

  private def showStackTrace(throwable: Throwable): Unit = {
    val sw = new StringWriter
    throwable.printStackTrace(new PrintWriter(sw))
    println(s"<LOG::-Stack Trace>${sw.toString.replaceAll("\n", "<:LF:>")}")
  }

  private def durationString(d: Option[Long]) = d map { _.toString } getOrElse ""
  private def replaceLF(s: String) = s.replaceAll("\n", "<:LF:>")
}

import org.scalatest.funsuite.AnyFunSuite
class TestFunSuite extends AnyFunSuite {

  test("An empty Set should have size 0") {
    assert(Set.empty.size == 0)
  }

  test("Invoking head on an empty Set should produce NoSuchElementException") {
    assertThrows[NoSuchElementException] {
      Set.empty.head
    }
  }
}

import org.scalatest.flatspec.AnyFlatSpec

class TestFlatSpec extends AnyFlatSpec {

  "An empty Set" should "have size 0" in {
    assert(Set.empty.size == 0)
  }

  it should "produce NoSuchElementException when head is invoked" in {
    assertThrows[NoSuchElementException] {
      Set.empty.head
    }
  }
}

import org.scalatest.funspec.AnyFunSpec

class TestFunSpec extends AnyFunSpec {

  describe("A Set") {
    describe("when empty") {
      it("should have size 0") {
        assert(Set.empty.size == 0)
      }

      it("should produce NoSuchElementException when head is invoked") {
        assertThrows[NoSuchElementException] {
          Set.empty.head
        }
      }
    }
  }
}

import org.scalatest.wordspec.AnyWordSpec

class TestWordSpec extends AnyWordSpec {

  "A Set" when {
    "empty" should {
      "have size 0" in {
        assert(Set.empty.size == 0)
      }

      "produce NoSuchElementException when head is invoked" in {
        assertThrows[NoSuchElementException] {
          Set.empty.head
        }
      }
    }
  }
}

import org.scalatest.freespec.AnyFreeSpec

class TestFreeSpec extends AnyFreeSpec {

  "A Set" - {
    "when empty" - {
      "should have size 0" in {
        assert(Set.empty.size == 0)
      }

      "should produce NoSuchElementException when head is invoked" in {
        assertThrows[NoSuchElementException] {
          Set.empty.head
        }
      }
    }
  }
}

import org.scalatest._
import org.scalatest.matchers._
import org.scalatest.propspec._
import org.scalatest.prop._
import org.scalatestplus.scalacheck._
import scala.collection.immutable._

class TestPropSpec extends AnyPropSpec with TableDrivenPropertyChecks with should.Matchers {

  val examples =
    Table(
      "set",
      BitSet.empty,
      HashSet.empty[Int],
      TreeSet.empty[Int]
    )

  property("an empty Set should have size 0") {
    forAll(examples) { set =>
      set.size should be (0)
    }
  }

  property("invoking head on an empty set should produce NoSuchElementException") {
    forAll(examples) { set =>
       a [NoSuchElementException] should be thrownBy { set.head }
    }
  }
}

import org.scalatest.featurespec._

class TVSet {
  private var on: Boolean = false
  def isOn: Boolean = on
  def pressPowerButton() = {
    on = !on
  }
}

class TestFeatureSpec extends AnyFeatureSpec with GivenWhenThen {

  info("As a TV set owner")
  info("I want to be able to turn the TV on and off")
  info("So I can watch TV when I want")
  info("And save energy when I'm not watching TV")

  feature("TV power button") {
    scenario("User presses power button when TV is off") {

      Given("a TV set that is switched off")
      val tv = new TVSet
      assert(!tv.isOn)

      When("the power button is pressed")
      tv.pressPowerButton()

      Then("the TV should switch on")
      assert(tv.isOn)
    }

    scenario("User presses power button when TV is on") {

      Given("a TV set that is switched on")
      val tv = new TVSet
      tv.pressPowerButton()
      assert(tv.isOn)

      When("the power button is pressed")
      tv.pressPowerButton()

      Then("the TV should switch off")
      assert(!tv.isOn)
    }
  }
}

import org.scalatest.refspec.RefSpec

class TestRefSpec extends RefSpec {

  object `A Set` {
    object `when empty` {
      def `should have size 0` = {
        assert(Set.empty.size == 0)
      }

      def `should produce NoSuchElementException when head is invoked` = {
        assertThrows[NoSuchElementException] {
          Set.empty.head
        }
      }
    }
  }
}

class RootSpec extends Sequential(
  new TestFunSuite,
  new TestFlatSpec,
  new TestFunSpec,
  new TestWordSpec,
  new TestFreeSpec,
  new TestPropSpec,
  new TestFeatureSpec,
  new TestRefSpec
)

class SuiteWithCodewarsReporter extends RootSpec
class SuiteWithHobovskysReporter extends RootSpec

object ScalaTEestsTest extends App {
  // (new TestFlatSpec).execute(color = false, configMap = ConfigMap("reporter" -> "CodewarsReporter"));
  (new SuiteWithCodewarsReporter).run(None, new Args(new CodewarsReporter));
  (new SuiteWithHobovskysReporter).run(None, new Args(new HobovskysReporter));
}
def dummy():Unit={}
def solution_function():
    return 0
Code
Diff
  • namespace Test {
      public class Test {
        public string a;
        public string b = null;
        
        public bool DummyMethod() {
          
          string local_a;
          string local_b = null;      
          return local_a == local_b;      
        }
        
      }
    }
    • namespace Test {
    • public class Test {
    • public string a;
    • public string b = null;
    • public bool DummyMethod() {
    • string local_a;
    • string local_b = null;
    • return local_a == local_b;
    • }
    • }
    • }

Looks like report of a test suite is not popped off the test result stack when a suite is completed.

Probably <COMPLETEDIN::> is missing.

let is_even n = n mod 2 == 0
Mathematics
Algorithms
Logic
Numbers

This kumite shows how to use stringizers to avoid confusing assertion messages in C++ tests.

For detailed description, see this Help article: Adding Custom Stringizers.

//See preloaded part for definition of stringizers

int test() { return 0; }