Is it possible to use guards in function definition in idris? - syntax

In haskell, one could write :
containsTen::Num a => Eq a => [a] -> Bool
containsTen (x : y : xs)
| x + y == 10 = True
| otherwise = False
Is it possible to write something equivalent in Idris, without doing it with ifThenElse (my real case is more complex than the one above)?

Idris does not have pattern guards exactly as in haskell. There is with clause which is syntactically similar (but more powerful as it supports matching in presence of dependent types):
containsTen : Num a => List a -> Bool
containsTen (x :: y :: xs) with (x + y)
| 10 = True
| _ = False
You can take a look at the Idris tutorial section 7 Views and the "with" rule.

Related

Check if number has its digits in order

I am trying to check if, given any number, its digits are in order. Example:
1479 -> TRUE
1293 -> FALSE
Is there a proper way to do this in Haskell? I am new to the language and feel really lost at the moment. Thank you.
I think #vps approach is proper enough but just for some variety you may also do the job as follows;
Prelude> and $ zipWith (<) <*> tail $ show 1479
True
Prelude> and $ zipWith (<) <*> tail $ show 1293
False
My idea is this:
ordenado n
| mod n 10 > mod (div n 10) 10 = ordenado (div n 10)
| n == 0 = True
| otherwise = False
You can convert it into String and use simple recursion and pattern matching.
checkInOrder :: Int -> Bool
checkInOrder x = isInOrder $ show x
isInOrder :: (Ord a) => [a] -> Bool
isInOrder [] = True
isInOrder [x] = True
isInOrder (x:y:xs) = (x < y) && (isInOrder (y:xs))
main = print (checkInOrder 1234)

a haskell function to test if an integer appears after another integer

I'm writing a function called after which takes a list of integers and two integers as parameters. after list num1 num2 should return True if num1 occurs in the list and num2 occurs in list afternum1. (Not necessarily immediately after).
after::[Int]->Int->Int->Bool
after [] _ _=False
after [x:xs] b c
|x==b && c `elem` xs =True
|x/=b && b `elem` xs && b `elem` xs=True
This is what I have so far,my biggest problem is that I don't know how to force num2 to be after num1.
There's a few different ways to approach this one; while it's tempting to go straight for recursion on this, it's nice to
avoid using recursion explicitly if there's another option.
Here's a simple version using some list utilities. Note that it's a Haskell idiom that the object we're operating over is usually the last argument. In this case switching the arguments lets us write it as a pipeline with it's third argument (the list) passed implicitly:
after :: Int -> Int -> [Int] -> Bool
after a b = elem b . dropWhile (/= a)
Hopefully this is pretty easy to understand; we drop elements of the list until we hit an a, assuming we find one we check if there's a b in the remaining list. If there was no a, this list is [] and obviously there's no b there, so it returns False as expected.
You haven't specified what happens if 'a' and 'b' are equal, so I'll leave it up to you to adapt it for that case. HINT: add a tail somewhere ;)
Here are a couple of other approaches if you're interested:
This is pretty easily handled using a fold;
We have three states to model. Either we're looking for the first elem, or
we're looking for the second elem, or we've found them (in the right order).
data State =
FindA | FindB | Found
deriving Eq
Then we can 'fold' (aka reduce) the list down to the result of whether it matches or not.
after :: Int -> Int -> [Int] -> Bool
after a b xs = foldl go FindA xs == Found
where
go FindA x = if x == a then FindB else FindA
go FindB x = if x == b then Found else FindB
go Found _ = Found
You can also do it recursively if you like:
after :: Int -> Int -> [Int] -> Bool
after _ _ [] = False
after a b (x:xs)
| x == a = b `elem` xs
| otherwise = after a b xs
Cheers!
You can split it into two parts: the first one will find the first occurrence of num1. After that, you just need to drop all elements before it and just check that num2 is in the remaining part of the list.
There's a standard function elemIndex for the first part. The second one is just elem.
import Data.List (elemIndex)
after xs x y =
case x `elemIndex` xs of
Just i -> y `elem` (drop (i + 1) xs)
Nothing -> False
If you'd like to implement it without elem or elemIndex, you could include a subroutine. Something like:
after xs b c = go xs False
where go (x:xs) bFound
| x == b && not (null xs) = go xs True
| bFound && x == c = True
| null xs = False
| otherwise = go xs bFound

Suggestions for reducing allocations (and work) in this Haskell function

I have the following function in my (much larger) Haskell code (with some supporting code to make it clear what's what):
import qualified Data.Set as S
import qualified Data.IntMap.Strict as M
import Data.Ord
import Data.Monoid
data Atom = Neg { index :: Int }
| Pos { index :: Int }
deriving (Eq, Ord, Show, Read)
newtype Clause = Clause { atoms :: S.Set Atom }
deriving (Eq, Show, Read)
instance Ord Clause where
compare = comparing (Down . S.size . atoms) <> comparing atoms
newtype Form = Form { clauses :: S.Set Clause }
deriving (Eq, Ord, Show, Read)
type Interpretation = M.IntMap Bool
-- the function of interest
interpret :: Interpretation -> Form -> Maybe Bool
interpret interp = evalForm
where evalAtom x#(Pos _) = M.lookup (index x) interp
evalAtom x#(Neg _) = not <$> M.lookup (index x) interp
evalClause (Clause x)
| S.member (Just False) evaluated = Just False
| evaluated == S.singleton (Just True) = Just True
| otherwise = Nothing
where evaluated = S.map evalAtom x
evalForm (Form x)
| S.member (Just True) evaluated = Just True
| evaluated == S.singleton (Just False) = Just False
| otherwise = Nothing
where evaluated = S.map evalClause x
Having profiled my Haskell program, I've found that this interpret function's allocations comprise nearly 40% of all allocations in my program (as well as about 40% of the CPU work).
Is there any way I can reduce either the amount of work interpret does, or the amount it allocates? This could potentially win me big performance gains (which I could really need, as I need to run this code many times, for experiments).
I would experiment with S.foldr.
From your code, it looks as if these are AND-clauses, so I will assume an empty clause is false.
evalClause (Clause x) = S.foldr f (Just False) $ S.map evalAtom x
where f b#(Just False) _ = b
f (Just True) y = y
f Nothing y#(Just False) = y
f Nothing y = Nothing
and the analogous for evalForm.
It might also be beneficial to use lists rather than sets. Sets, as implemented, are strict, and (I think) will not trigger some optimizations like fusion/deforestation/etc. Lists are lazily produced, and should behave better in this sort of code.
evalClause (Clause x) = foldr f (Just False) . map evalAtom $ S.toList x
...
An observation:
A Maybe Bool can only have three possible values - Nothing, Just False and Just True.
evaluated in both evalClause and evalForm has type Set (Maybe Bool) which can be represented with three bits which fits in a Int.
I would define:
data MaybeBool = Nuthin | JustFalse | JustTrue
deriving (Eq, Ord, Enum, Bounded, Show, Read)
and change the signature of intepret return a MaybeBool
Then define evaluated as a bitset like this:
import Data.Bits
evaluated = foldl' combine 0 (map evalAtom (S.toList x))
where combine s a = s .|. (1 `shiftLeft` fromEnum a)
evaluated will be a Int between 0 and 7 with bit 0 set if Nutin is in the set, bit 1 set if JustFalse is in the set and bit 2 set if JustTrue is in the set. This will eliminate allocation of Sets from your computation.

Defining Unlambda-style tree notation in Coq

Here is a definition of polymorphic binary trees I am using in a Coq project.
Inductive tree { X : Type } : Type :=
| t_a : X -> tree
| t_m : tree -> tree -> tree.
A binary tree of natural numbers ( 1 ( ( 2 3 ) 4 ) ), declared using this definition, would be:
t_m ( t_a 1 ) ( t_m ( t_m ( t_a 2 ) ( t_a 3 ) ) ( t_a 4 ) )
As you can see, the definition becomes unusable very quickly with increasing number of leaves. What I want to do is define an Unlambda-style notation for trees so that I can replace the above with
' 1 ' ' 2 3 4
Is this possible?
I tried to get a solution that used only Coq notations, but couldn't get it to work. I suspect that Coq's extensible parser is not powerful enough to understand the notation you want. There is, however, a poor man's solution that involves dependent types. The idea is to write a parser for that notation and use that parser's type to encode the parser state. The type says that the parser "reads" some token (actually, takes that token as an argument to a function call), and goes into some next state that depends on the token it just read.
There's a small subtlety, though, which is that one cannot write that type using just regular Coq function types, because the number of arguments that function would take would depend on all the arguments it is being applied to. One solution is to use a coinductive type to encode this behavior, declaring a coercion to make it look like a function:
Inductive tree (X : Type) : Type :=
| t_a : X -> tree X
| t_m : tree X -> tree X -> tree X.
Arguments t_a {X} _.
Arguments t_m {X} _ _.
CoInductive tree_builder X : nat -> Type :=
| TbDone : tree X -> tree_builder X 0
| TbRead : forall n, (forall o : option X, tree_builder X match o with
| Some x => n
| None => S (S n)
end) ->
tree_builder X (S n).
Arguments TbDone {X} _.
Arguments TbRead {X} _ _.
(* Destructors for tree_builder *)
Definition case0 {X} (x : tree_builder X 0) : tree X :=
match x with
| TbDone t => t
end.
Definition caseS {X n} (x : tree_builder X (S n)) :
forall o : option X, tree_builder X match o with
| Some x => n
| None => S (S n)
end :=
match x with
| TbRead _ f => f
end.
Definition tb X n := tree_builder X (S n).
(* force is what does the magic here: it takes a tb and coerces it to a
function that may produce another tb, depending on what it is applied to. *)
Definition force X n (x : tb X n) : forall o : option X,
match o with
| Some x =>
match n with
| 0 => tree X
| S n' => tb X n'
end
| None =>
tb X (S n)
end :=
fun o =>
match o return tree_builder X match o with
| Some x => n
| None => S (S n)
end ->
match o with
| Some x => match n with
| 0 => tree X
| S n' => tb X n'
end
| None => tb X (S n)
end
with
| Some x => match n return tree_builder X n -> match n with
| 0 => tree X
| S n' => tb X n'
end
with
| 0 => fun t => case0 t
| S _ => fun t => t
end
| None => fun t => t
end (caseS x o).
Coercion force : tb >-> Funclass.
Our parser, then, is just a term of type tb X 0. As it is usually done, it has to be written in continuation-passing style because of the variable number of arguments.
Fixpoint parser_cont_type X (n : nat) : Type :=
match n with
| 0 => tree X
| S n' => tree X -> parser_cont_type X n'
end.
CoFixpoint parser X n : parser_cont_type X n -> tree_builder X n :=
match n with
| 0 => fun k => TbDone k
| S n' => fun k : tree X -> parser_cont_type X n' =>
TbRead n' (fun o => match o return tree_builder X match o with
| Some _ => n'
| None => S (S n')
end
with
| Some x => parser X n' (k (t_a x))
| None => parser X (S (S n')) (fun (t1 t2 : tree X) => k (t_m t1 t2))
end)
end.
Definition parser' X : tb X 0 :=
parser X 1 (fun t => t).
Next, we can define some extra notation to make this easier to use:
Notation "[ x ]" := (Some x) (at level 0).
Notation "''" := None (at level 0).
Notation "!" := (parser' _) (at level 20).
Here's how one could write your example tree, for instance:
Definition my_tree : tree nat := Eval hnf in ! '' [1] '' '' [2] [3] [4].
Notice the initial ! to start a call to the parser, and the [] that are needed to mark the leaves. I also couldn't get Coq's parser to accept ' as a token on its own. Besides these minor details, however, it is fairly close to what you had.
One problem is that, because the parser is defined using Coq functions, one needs to do a little bit of simplification to get a term that is exactly like the one you had originally. This is why I added the Eval call on the definition. This is probably not as practical as a real notation, and the definition is admittedly a bit tricky, but it could be pretty useful for some cases.
Here's a gist with the entire .v file.
UPDATE: I've written a post with a much simplified version of this technique made more generic.

Functional "All except one"

How I can declare function that takes number and list of numbers, and returns NONE if there is no such number in the list, otherwise returns list option ('Maybe' in Haskell) without this number? If there more then one such number, function has to erase just first of them.
all_except_one : 'a * 'a list -> 'a list option
I have no idea how to do it :\
I ask any code in any language, just some tip about algorithm in functional style (initially I have to solve this problem in SML). Also I can't use higher order functions in my task.
what about this solution ?
fun all_except_one(s, lst) =
let
fun helper e =
case e of
([], _) => NONE
|(x::xs, acc) => if x = s
then SOME (acc # xs)
else helper(xs, x :: acc)
in helper(lst, []) end
The same without helper function and without tail recursion.
fun all_except_one (_, []) = NONE
| all_except_one (s, x::xs) = if x = s
then SOME xs
else case all_except_one(s, xs) of
NONE => NONE
| SOME ys => SOME (x::ys)
How about (Haskell syntax):
allbutone n xs
| n `elem` xs = Just (filter (!=n) xs)
| otherwise = Nothing

Resources