Skip to content

Instantly share code, notes, and snippets.

@vysakh0
Created February 9, 2016 04:04
Show Gist options
  • Save vysakh0/4b76c1976106b679d910 to your computer and use it in GitHub Desktop.
Save vysakh0/4b76c1976106b679d910 to your computer and use it in GitHub Desktop.
A simple palindrome without using any inbuilt functions like `String.reverse` or `String.length`
defmodule Palindrome do
def check(<< first :: binary-size(1), rest :: binary >> = actual) do
check(first, rest, actual)
end
def check(newstr, << next_letter :: binary-size(1), rest :: binary >>, actual) do
check(next_letter <> newstr, rest, actual)
end
def check(reverse, <<>>, actual), do: reverse === actual
end
defmodule PalindromeTest do
use ExUnit.Case
test "check if palindrome" do
assert Palindrome.check("elixir") === false
assert Palindrome.check("madam") === true
end
end
@5hanth
Copy link

5hanth commented Feb 9, 2016

Bottom case

  • assert Palindrome.check("") === true
  • assert Palindrome.check(" ") === true
> Palindrome.check ""
** (FunctionClauseError) no function clause matching in Palindrome.check/1
    Palindrome.ex:2: Palindrome.check("")

clojure-version

(defn palin?
  ([actual]
   (palin? actual actual ""))
  ([[first & rest] actual reverse]
   (if (= nil first)
     (= actual reverse)
     (palin? rest actual (str first reverse)))))

(deftest check-palindrome
  (is (not= (palin? "clojure") true))
  (is (= (palin? "aibohphobia") true))
  (is (= (palin? "") true))
  (is (= (palin? " ") true)))

(run-tests)

haskell-version

-- | Check Palindrome 

module Palindrome where

check :: [a] -> Bool
check actual = check_ actual actual []
               where
                 check_ [] actual reverse = actual == reverse
                 check_ (x:xs) actual reverse = check_ xs actual (x:reverse)

elixir-version

defmodule Palindrome do
  def check(actual) do
    check(actual, actual, "")
  end

  def check(<< next_letter :: binary-size(1), rest :: binary >>, actual, reverse) do
    check(rest, actual, next_letter <> reverse)
  end

  def check(<<>>, actual, reverse), do: reverse === actual
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment