0

I'm very new to Idris (and dependent types). I was trying to do write a program to check if a string is a palindrome of not. To do that, I decided to compute the length of the string, and compute

q,r = (strlen `div` 2, strlen `mod` 2)

and then split the string as follows:

lhalf,rhalf = (substr 0 (q+r) str, substr (q-r) (q+r) str)

This takes care of both odd and even length strings. The problem is that Idris needs a proof that r < q since both q and r are Nat.

My question is: How do I express the fact that r

Here's the full sample of my code:

module Main

isPalindrome : (str : String) -> String
isPalindrome str =
  let split = half_half str
  in show ((fst split) == reverse (snd split))
  where
    strlen : Nat
    strlen = length str

    divMod : Nat -> Nat -> (Nat,Nat)
    divMod x y = (x `div` y, x `mod` y)

    half_half : String -> (String, String)
    half_half "" = ("","")
    half_half x  = let
                     (q,r) = divMod strlen 2
                   in
                     (substr 0     (q+r) x,
                      substr (q-r) (q+r) x)

main : IO ()
main = repl "> " isPalindrome

1 Answers1

2

You can't proof that r ≤ q because it's not true. For example, given the string "a" you have strlen = 1 and therefore q = 0 and r = 1. In this example r ≤ q is clearly false.

Note that you can implement isPalindrome simply by

isPalindrome: String -> Bool
isPalindrome str = str == reverse str
Gregg54654
  • 150
  • 8
  • I realized that minutes after posting it. Catching this sort of thing is precisely why we need dependent types. But suppose that I do have a pair (p,r) such that r < p. How do I express this fact in terms of types? – MachPortMassenger Oct 01 '17 at 03:45
  • 1
    One way of doing this is that you construct a proof for this fact. The type `LT r p` represents these proofs, meaning you have to create an instance of `LT r p`. How you construct such an instance depends on where the values come from and why you actually know that r is less than p. – Gregg54654 Oct 01 '17 at 11:14