named implementation to default implementation - typeclass

I defined a named implementation for the typeclass Ord for type Int.
[mijnOrd] Ord Int where
compare n1 n2 = ...
How can I import this named implementation and use it as "default"
so in another module I want to import this implementation
Mark it as default
And use it as if it was default
--
sort [1,5,2] -- output without importing as default: [1,2,5]
sort [1,5,2] -- output with importing as default: [5,2,1]
Is this possible in Idris?

This is possible since Idris 0.12 using using-blocks:
Export your named interface in one module, say MyOrd.idr:
module MyOrd
-- Reverse order for `Nat`
export
[myOrd] Ord Nat where
compare Z Z = EQ
compare Z (S k) = GT
compare (S k) Z = LT
compare (S k) (S j) = compare #{myOrd} k j
Then just import it in another module and wrap everything that should use it as default in a corresponding using-block like so:
-- Main.idr
module Main
import MyOrd
using implementation myOrd
test : List Nat -> List Nat
test = sort
main : IO ()
main = putStrLn $ show $ test [3, 1, 2]
This should print [3, 2, 1].

Related

Flatten randomly nested list into a non nested list using Haskell

I have an imaginary list with different levels of nesting, or ignoring the ugly types a API response ie:
a ::(Num a, Num [a], Num [[a]]) => [[a]]
a = [1, 2, [3, 4]]
b :: (Num a, Num [a], Num [[a]], Num [[[a]]]) => [[[[a]]]]
b = [[1,2,[3]],4]
The function I'm trying to create should do the following:
myFunc a == [1,2,3,4]
myFunc b == [1,2,3,4]
My initial thought was I'd have to parse the list into an AST (Abstract syntax tree) --> use recursion to flatten all the branches & leaves into a single branch --> parse the result back into a list.
I'm unsure how to parse the list into AST? or is there a better solution?
edit -- I think I was trying to be too literal, in that representing [1, 2, [3, 4]] is actually part of the problem, so realistically for things to work better they would need to be represented as an ADT/AST. So if this was an API response or reading a file how would I parse that data into it's AST/ADT?
An arbitrarily nested list won't type check. Each element of a list has to have the same type, but lists with different nesting levels have different types. The trick to get around this is to wrap a list into a new data type that hides the number of nested levels. But this is just a tree.
data Tree a = Root a | Branches [Tree a]
Then you can implement flatten as a traversal of the tree.
flatten :: Tree a -> [a]
flatten (Root a) = [a]
flatten (Branches (t:ts)) = flatten t ++ (concat (fmap flatten ts))
See Data.Tree in the containers package for a ready-to-use version.
For parsing, I would recommend using aeson. Data.Aeson.Types defines the instance FromJSON v => FromJSON (Tree v), so you should just be able to use decode on the json string and tell it you want a Tree Int.
decode rawJson :: Maybe (Tree Int)
This is already done for you by the GHC. Flattening is folding.
> :set -XDeriveFoldable
> data NList a = A a | N [NList a] deriving (Show, Functor, Foldable)
data NList a = A a | N [NList a]
> foldMap pure (N[ A 1, N[ A 2], A 3]) :: [Int]
[1,2,3]
> foldMap pure (N[ N[ N[ N[ A 1]]], N[ A 2], A 3]) :: [Int]
[1,2,3]
Unclear what you're actually trying to achieve, but there is a syntax hack that actually allows you to write differently-nested list syntax in Haskell and have it flattened automatically:
{-# LANGUAGE TypeFamilies #-}
import GHC.Exts (IsList(..))
newtype AutoflatList a = AutoflatList {getFlatList :: [a]}
deriving (Show)
instance IsList (AutoflatList a) where
type Item (AutoflatList a) = AutoflatList a
fromList segs = AutoflatList $ getFlatList =<< segs
toList = pure
instance Num a => Num (AutoflatList a) where
fromInteger = AutoflatList . pure . fromInteger
*Main> :set -XOverloadedLists
*Main> [1, 2, [3, 4]] :: AutoflatList Int
AutoflatList {getFlatList = [1,2,3,4]}
*Main> [[1,2,[3]],4] :: AutoflatList Int
AutoflatList {getFlatList = [1,2,3,4]}
This solution not recommended except for recreational purposes.

Open a particular instance in `where` statement in Agda

When I write a lot of agda code I always end up having this cumbersome pattern in my code. Suppose I have this record type defining a mathematical structure:
record A (T : Set) : Set where
m1 = -- ...
m2 = -- ...
m3 = -- ...
field
f1 : -- ...
f2 : -- ...
f3 : -- ...
then I prove a property of this structure A:
theorem : ∀ {S} -> A S -> -- ...
theorem a = -- ...
where
m1 = A.m1 a
m2 = A.m2 a
f1 = A.f1 a
f2 = A.f2 a
-- ...
This is very annoying. I could open A but then I just have m1, m2 that maps a to the object I want. I want something like open a so that m1 refers directly to (A.m1 a). I couldn't find anything on this matter in Agda documentation. Is there such syntactic sugar? This problem is responsible of great majority (maybe >60% of my code). In every single theorem I open up the whole structure... What am I doing wrong? How can I fix this?

How dangerous is trustMe?

Here's what I understand about Relation.Binary.PropositionalEquality.TrustMe.trustMe: it seems to take an arbitrary x and y, and:
if x and y are genuinely equal, it becomes refl
if they are not, it behaves like postulate lie : x ≡ y.
Now, in the latter case it can easily make Agda inconsistent, but this in itself is not so much a problem: it just means that any proof using trustMe is a proof by appeal to authority. Moreover, though you can use such things to write coerce : {A B : Set} -> A -> B, it turns out to be the case that coerce {ℕ} {Bool} 0 doesn't reduce (at least, not according to C-c C-n), so it's really not analogous to, say, Haskell's semantic-stomping unsafeCoerce.
So what do I have to fear from trustMe? On the other hand, is there ever a reason to use it outside of implementing primitives?
Indeed, attempting to pattern match on trustMe which does not evaluate to refl results in a stuck term. Perhaps it is enlightening to see (part of) the code that defines the primitive operation behind trustMe, primTrustMe:
(u', v') <- normalise (u, v)
if (u' == v') then redReturn (refl $ unArg u) else
return (NoReduction $ map notReduced [a, t, u, v])
Here, u and v represent the terms x and y, respectively. The rest of the code can be found in the module Agda.TypeChecking.Primitive.
So yes, if x and y are not definitionally equal, then primTrustMe (and by extension trustMe) behaves as a postulate in the sense that evaluation simply gets stuck. However, there's one crucial difference when compiling Agda down to Haskell. Taking a look at the module Agda.Compiler.MAlonzo.Primitives, we find this code:
("primTrustMe" , Right <$> do
refl <- primRefl
flip runReaderT 0 $
term $ lam "a" (lam "A" (lam "x" (lam "y" refl))))
This looks suspicious: it always returns refl no matter what x and y are. Let's have a test module:
module DontTrustMe where
open import Data.Nat
open import Data.String
open import Function
open import IO
open import Relation.Binary.PropositionalEquality
open import Relation.Binary.PropositionalEquality.TrustMe
postulate
trustMe′ : ∀ {a} {A : Set a} {x y : A} → x ≡ y
transport : ℕ → String
transport = subst id (trustMe {x = ℕ} {y = String})
main = run ∘ putStrLn $ transport 42
Using trustMe inside transport, compiling the module (C-c C-x C-c) and running the resulting executable, we get... you guessed it right - a segfault.
If we instead use the postulate, we end up with:
DontTrustMe.exe: MAlonzo Runtime Error:
postulate evaluated: DontTrustMe.trustMe′
If you do not intend to compile your programs (at least using MAlonzo) then inconsistency should be your only worry (on the other hand, if you only typecheck your programs then inconsistency usually is kind of a big deal).
There are two use cases I can think of at the moment, first is (as you've said) for implementing primitives. The standard library uses trustMe in three places: in implementation of decidable equality for Names (Reflection module), Strings (Data.String module) and Chars (Data.Char module).
The second one is much like the first one, except that you provide the data type and the equality function yourself and then use trustMe to skip the proving and just use the equality function to define a decidable equality. Something like:
open import Data.Bool
open import Relation.Binary
open import Relation.Binary.PropositionalEquality
open import Relation.Nullary
data X : Set where
a b : X
eq : X → X → Bool
eq a a = true
eq b b = true
eq _ _ = false
dec-eq : Decidable {A = X} _≡_
dec-eq x y with eq x y
... | true = yes trustMe
... | false = no whatever
where postulate whatever : _
However, if you screw up eq, the compiler cannot save you.

Invertible State monad (and parsers)

Good day, ladies and gentlemen!
I'm constantly writing parsers and codecs. Implementing both parsers and printers seems to be massive code duplication. I wonder whether it is possible to invert a stateful computation, given it is isomorphic by nature.
It is possible to invert pure function composition (Control.Lens.Iso did that by defining a composition operator over isomorphisms). As it can be observed,
Iso bc cb . Iso ab ba = Iso (bc . ab) (ba . cb) -- from Lenses talk
invert (f . g) = (invert g) . (invert f) -- pseudo-code
In other words, to invert a function composition one should compose inverted functions in the opposite order. So, given all primitive isomorphic pairs are defined, one can compose them to get more complicated pairs with no code duplication. Here is an example of pure bidirectional computation (Control.Lens is used, the explanatory video can help you to get the general idea of Lenses, Folds and Traversals):
import Control.Lens
tick :: Num a => Iso' a a
tick = iso (+1) (subtract 1) -- define an isomorphic pair
double :: Num a => Iso' a a
double = iso (+2) (subtract 2) -- and another one
threeTick :: Num a => Iso' a a
-- These are composed via simple function composition!
threeTick = double . tick
main :: IO ()
main = do
print $ (4 :: Int)^.tick -- => 5
print $ (4 :: Int)^.from tick -- => 3
print $ (4 :: Int)^.threeTick -- => 7, Composable
print $ (4 :: Int)^.from threeTick -- => 1, YEAH
As you can see, I didn't need to supply the inverted version of threeTick; it is obtained by backward composition automatically!
Now, let's consider a simple parser.
data FOO = FOO Int Int deriving Show
parseFoo :: Parser FOO
parseFoo = FOO <$> decimal <* char ' '
<*> decimal
parseFoo' :: Parser FOO
parseFoo' = do
first <- decimal
void $ char ' '
second <- decimal
return $ FOO first second
printFoo :: FOO -> BS.ByteString
printFoo (FOO a b) = BS.pack(show a) <>
BS.pack(" ") <>
BS.pack(show b)
main :: IO ()
main = do
print $ parseOnly parseFoo "10 11" -- => Right (FOO 10 11)
print $ parseOnly parseFoo' "10 11" -- => Right (FOO 10 11)
print . printFoo $ FOO 10 11 -- => "10 11"
print . parseOnly parseFoo . printFoo $ FOO 10 11 -- id
You can see that both versions of parseFoo are fairly declarative (thanks to parser combinators). Note the similarity between parseFoo and printFoo. Can I define isomorphisms over primitive parsers (decimal and char) and then just derive the printer (printFoo :: FOO -> String) automatically? Ideally, parser combinators will work as well.
I tried to redefine a monadic >>= operator in order to provide inverted semantics, but I've failed to do so. I feel that one could define inverted Kleisli composition operator (monadic function composition) similarly to composition inversion, but can one use it with ordinary monads?
f :: a -> m b, inverse f :: b -> m a
g :: b -> m c, inverse g :: c -> m b
inverse (f >=> g) = (inverse f) <=< (inverse g)
Why inverse f is of type b -> m a and not m b -> a? The answer is: monadic side effect is an attribute of an arrow, not that of a data type b. The state monad dualization is further discussed in the great Expert to Expert video.
If the solution does exist, could you please supply a working example of printFoo derivation? By the way, here is an interesting paper that could help us find the solution.
You may be interested in digging in further into the lens package for the concept of a Prism.
A Prism can be used as a 'smart constructor' to build something (e.g. a pretty printed string) unconditionally, and match on it (e.g. parse).
You'd have to ignore the laws or treat the laws as holding only up to a quotient though, as the string you get out of pretty printing is very likely not exactly the string you parsed.

Is it possible to have F# module abbreviations in a function or value binding?

In the following ML extract (taken from the Effective ML talk), there is a module abbreviation inside a value binding expression. Is it possible to do the equivalent in F#? I know you can do module abbreviations, I am specifically interested if you can do them "inline" like this.
let command =
let default_config = { exit_code = 0; message = None } in
let flags =
let module F = Command.Flag in
[ F.int "-r" (fun cfg v -> { cfg with exit_code = v });
F.string "-m" (fun cfg v -> { cfg with message = v });
]
...
No, this feature is not available in F#. You can only do top-level module abbreviations (as you say) using:
module F = Command.Flag
You can write these in the middle of a source file, but they have to be at the top-level and their scope is always going to be until the end of a file (or until another definition that hides F). Perhaps if you used this and then had another definition hiding F, it would have similar effect. For example:
module L = List
[0 .. 9] |> L.map ((*) 2) // Uses functional `List.map`
module L = Seq
[0 .. 9] |> L.map ((*) 2) // Uses lazy `Seq.map`
I agree taht this would be a useful feature in many cases - on the other hand, the F# programming style is sufficiently different from ML, so the advices from Effective ML talk may not directly map to F# programming. If you need to make something a local definition, then the best option would be to define it as an F# object.

Resources