logo
down
shadow

Scala typeclass without function argument


Scala typeclass without function argument

By : Pratik
Date : November 18 2020, 03:49 PM
seems to work fine I'm currently working on my network library in scala. I encountered something like this: , Prepend an empty parameter list:
code :
def read[T]()(implicit e: Reader[T]): T =
  e.read(iterator)

def readByte(): Byte =
  this.read[Byte]()  // <- HURRAY IT WORKS


Share : facebook icon twitter icon
Transform a function with a typeclass constraint into a function taking an explicit typeclass dictionary

Transform a function with a typeclass constraint into a function taking an explicit typeclass dictionary


By : Harsha Manchu
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further For the record, I thought I would explain the 'hacky' solution to this which I already know of. I'll basically illustrate it using a series of examples. So let's imagine we're trying to reify the classes, instances and functions in the following (which consists mostly of pretty standard typeclasses, generally simplified somewhat for the exposition):
code :
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}

module Src where

import Data.List (intercalate)

class SimpleShow a where
  sshow :: a -> String

class SimpleMonoid a where
  mempty  :: a
  mappend :: a -> a -> a

class SimpleFunctor f where
  sfmap :: (a -> b) -> f a -> f b

instance SimpleShow Int where
  sshow = show

instance SimpleMonoid [a] where
  mempty  = []
  mappend = (++)

instance SimpleMonoid ([a], [b]) where
  mempty  = ([], [])
  mappend (a1, b1) (a2, b2) = (a1 ++ a2, b1 ++ b2)

instance SimpleFunctor [] where
  sfmap = map
show_2lists :: (SimpleShow a) => [a] -> [a] -> String
show_2lists as1 as2 = "[" ++ intercalate ", " (map sshow as1) ++ "]/["
                      ++ intercalate ", " (map sshow as2) ++ "]"

mconcat :: (SimpleMonoid a) => [a] -> a
mconcat = foldr mappend mempty

example :: (SimpleMonoid (x, y)) => [(x, y)] -> (x, y)
example = foldr mappend mempty

lift_all :: (SimpleFunctor f) => [a -> b] -> [f a -> f b]
lift_all = map sfmap
{-# LANGUAGE PatternGuards #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE EmptyDataDecls #-}
{-# LANGUAGE UndecidableInstances  #-}
{-# LANGUAGE FlexibleInstances #-}

module Main where

import Unsafe.Coerce
import Src

data Proxy k = Proxy

class Reifies s a | s -> a where
  reflect :: proxy s -> a

newtype Magic a r = Magic (forall (s :: *). Reifies s a => Proxy s -> r)

reify :: forall a r. a -> (forall (s :: *). Reifies s a => Proxy s -> r) -> r
reify a k = unsafeCoerce (Magic k :: Magic a r) (const a) Proxy
{-# INLINE reify #-}


data SimpleShow_    a = SimpleShow_    {sshow_  :: a -> String}
data SimpleMonoid_  a = SimpleMonoid_  {mempty_ :: a,
                                        mappend_ :: a -> a -> a}
data SimpleFunctor_ f = SimpleFunctor_ {
  sfmap_  :: forall a b. (a -> b) -> (f a -> f b)
  }

instance_SimpleShow_Int :: SimpleShow_ Int
instance_SimpleShow_Int = SimpleShow_ sshow

instance_SimpleMonoid_lista :: SimpleMonoid_ [a]
instance_SimpleMonoid_lista =  SimpleMonoid_ mempty mappend

instance_SimpleMonoid_listpair :: SimpleMonoid_ ([a], [b])
instance_SimpleMonoid_listpair =  SimpleMonoid_ mempty mappend

instance_SimpleFunctor_list :: SimpleFunctor_ []
instance_SimpleFunctor_list = SimpleFunctor_ sfmap

---------------------------------------------------------------------
--code to reify show_2lists :: (SimpleShow a) => [a] -> [a] -> String

-- for each type variable that occurs in the constraints, we must
-- create a newtype. Here there is only one tpye variable ('a') so we
-- create one newtype.
newtype Wrap_a a s  = Wrap_a { extract_a :: a }

-- for each constraint, we must create an instance of the
-- corresponding typeclass where the instance variables have been
-- replaced by the newtypes we just made, as follows.
instance Reifies s (SimpleShow_ a) => SimpleShow (Wrap_a a s) where
  --sshow :: (Wrap_ a s) -> String
  sshow = unsafeCoerce sshow__
    where sshow__ :: a -> String
          sshow__ = sshow_ $ reflect (undefined :: [] s)

-- now we can reify the main function
show_2lists_ :: forall a. SimpleShow_ a -> [a] -> [a] -> String
show_2lists_ dict = let
  magic :: forall s. ([Wrap_a a s] -> [Wrap_a a s] -> String)
           -> Proxy s -> ([a] -> [a] -> String)
  magic v _ arg1 arg2 = let
    w_arg1 :: [Wrap_a a s]
    w_arg1 =  unsafeCoerce (arg1 :: [a])

    w_arg2 :: [Wrap_a a s]
    w_arg2 =  unsafeCoerce (arg2 :: [a])

    w_ans :: String
    w_ans = v w_arg1 w_arg2

    ans   :: String
    ans   = unsafeCoerce w_ans
    in ans

  in (reify dict $ magic show_2lists)

---------------------------------------------------------------------
--code to reify mconcat :: (SimpleMonoid a) => [a] -> a

-- Here the newtypes begin with Wrap1 to avoid name collisions with
-- the ones above
newtype Wrap1_a a s  = Wrap1_a { extract1_a :: a }
instance Reifies s (SimpleMonoid_ a) => SimpleMonoid (Wrap1_a a s) where
  --mappend :: (Wrap1_a a s) -> (Wrap1_a a s) -> (Wrap1_a a s)
  mappend = unsafeCoerce mappend__
    where mappend__ :: a -> a -> a
          mappend__ =  (mappend_ $ reflect (undefined :: [] s))
  --mempty  :: (Wrap1_a a s)
  mempty = unsafeCoerce mempty__
    where mempty__  :: a
          mempty__  =  (mempty_  $ reflect (undefined :: [] s))

mconcat_ :: forall a. SimpleMonoid_ a -> [a] -> a
mconcat_ dict = let
  magic :: forall s. ([Wrap1_a a s] -> (Wrap1_a a s)) -> Proxy s -> ([a] -> a)
  magic v _ arg1 = let
    w_arg1 :: [Wrap1_a a s]
    w_arg1 =  unsafeCoerce (arg1 :: [a])

    w_ans :: Wrap1_a a s
    w_ans = v w_arg1

    ans   :: a
    ans   = unsafeCoerce w_ans
    in ans

  in (reify dict $ magic mconcat)

---------------------------------------------------------------------
--code to reify example :: (SimpleMonoid (x, y)) => [(x, y)] -> (x, y)

newtype Wrap2_x x s  = Wrap2_x { extract2_x :: x }
newtype Wrap2_y y s  = Wrap2_y { extract2_y :: y }
instance Reifies s (SimpleMonoid_ (x, y))
         => SimpleMonoid (Wrap2_x x s, Wrap2_y y s) where
  --mappend :: (Wrap2_x x s, Wrap2_y y s) -> (Wrap2_x x s, Wrap2_y y s)
  --                 -> (Wrap2_x x s, Wrap2_y y s)
  mappend = unsafeCoerce mappend__
    where mappend__ :: (x, y) -> (x, y) -> (x, y)
          mappend__ =  (mappend_ $ reflect (undefined :: [] s))
  --mempty  :: (Wrap2_x x s, Wrap2_y y s)
  mempty = unsafeCoerce mempty__
    where mempty__  :: (x, y)
          mempty__  =  (mempty_  $ reflect (undefined :: [] s))

example_ :: forall x y. SimpleMonoid_ (x, y) -> [(x, y)] -> (x, y)
example_ dict = let
  magic :: forall s. ([(Wrap2_x x s, Wrap2_y y s)] -> (Wrap2_x x s, Wrap2_y y s))
           -> Proxy s -> ([(x, y)] -> (x, y))
  magic v _ arg1 = let
    w_arg1 :: [(Wrap2_x x s, Wrap2_y y s)]
    w_arg1 =  unsafeCoerce (arg1 :: [(x, y)])

    w_ans :: (Wrap2_x x s, Wrap2_y y s)
    w_ans = v w_arg1

    ans   :: a
    ans   = unsafeCoerce w_ans
    in ans

  in (reify dict $ magic mconcat)

---------------------------------------------------------------------
--code to reify lift_all :: (SimpleFunctor f) => [a -> b] -> [f a -> f b]

newtype Wrap_f f s d = Wrap_f { extract_fd :: f d}
instance Reifies s (SimpleFunctor_ f) => SimpleFunctor (Wrap_f f s) where
  --sfmap :: (a -> b) -> (Wrap_f f s a -> Wrap_f f s b)
  sfmap = unsafeCoerce sfmap__
    where sfmap__ :: (a -> b) -> (f a -> f b)
          sfmap__ = sfmap_ $ reflect (undefined :: [] s)

lift_all_ :: forall a b f. SimpleFunctor_ f -> [a -> b] -> [f a -> f b]
lift_all_ dict = let
  magic :: forall s. ([a -> b] -> [Wrap_f f s a -> Wrap_f f s b])
           -> Proxy s -> ([a -> b] -> [f a -> f b])
  magic v _ arg1 = let
    w_arg1 :: [a -> b]
    w_arg1 =  unsafeCoerce (arg1 :: [a -> b])

    w_ans :: [Wrap_f f s a -> Wrap_f f s b]
    w_ans = v w_arg1

    ans   :: [f a -> f b]
    ans   = unsafeCoerce w_ans
    in ans

  in (reify dict $ magic lift_all)

main :: IO ()
main = do
  print (show_2lists_ instance_SimpleShow_Int     [3, 4] [6, 9])
  print (mconcat_     instance_SimpleMonoid_lista [[1, 2], [3], [4, 5]])
  print (example_     instance_SimpleMonoid_listpair
                                     [([1, 2], ["a", "b"]), ([4], ["q"])])
  let fns' :: [[Int] -> [Int]]
      fns' = lift_all_ instance_SimpleFunctor_list [\ x -> x+1, \x -> x - 1]
  print (map ($ [5, 7]) fns')


{- output:

"[3, 4]/[6, 9]"
[1,2,3,4,5]
([1,2,4],["a","b","q"])
[[6,8],[4,6]]

-}
Why can't Scala find my typeclass instance defined implicitly in the companion object, when the typeclass is not in a de

Why can't Scala find my typeclass instance defined implicitly in the companion object, when the typeclass is not in a de


By : Manuel Ramiro Moreta
Date : March 29 2020, 07:55 AM
I wish did fix the issue. There's a rule that implicit has to be defined earlier in the compilation unit.
So, move object Show to the top and it compiles.
code :
object Show {
  //implicit object StringShow extends Show[String] {
  implicit val x: Show[String] = new Show[String] {
    def show(s: String) = s"[String: $s]"
  }
}
Using multiple Scala TypeClass instances in function parameters

Using multiple Scala TypeClass instances in function parameters


By : Hani Rosidaini
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further Update
If you only want to define AS[I, P] instances for particular values of I and P, that's also possible—you can define ASQueryBuilder as in your question, and then require an instance in your methods that use the type class:
code :
def func(a: A, s: S)(implicit bq: BuildableQuery[AS[A, S]]): QueryBuilder = toQuery(AS(a,s))

def func2[I <: A: BuildableQuery, P <: S: BuildableQuery](a: I, s: P)(implicit
  bq: BuildableQuery[AS[I, P]]
): QueryBuilder = toQuery(AS(a, s))
implicit def ASQueryBuilder[I <: A, P <: S]: BuildableQuery[AS[I, P]] =
  new BuildableQuery[AS[I, P]] { 
    def toQuery(p: AS[I, P]): QueryBuilder = { QueryBuilder("Query of AS") }
}
Coq won't compute a typeclass function if the typeclass has a Prop

Coq won't compute a typeclass function if the typeclass has a Prop


By : Nur Rohman
Date : March 29 2020, 07:55 AM
Does that help This happened because you've used Qed instead of Defined to finish the definition of class2_instance. Qed renders your definition opaque, making computation impossible.
The following works:
code :
Instance class2_instance : class2 := { class_func2 := S }.
Proof. trivial. Defined.

Compute class_func2 5.  (* returns 6 *)
Definition id (x : nat) : nat.
  exact x. Qed.
How to subject the function argument to typeclass instantiation?

How to subject the function argument to typeclass instantiation?


By : Kaya Casper
Date : March 29 2020, 07:55 AM
Hope this helps Okay, I can do this: , Yes, but only with a newtype:
code :
newtype BackFun a b = BackFun (b -> a)

instance Fun (BackFun a) where
  fm g (BackFun f) = BackFun (f . g)
type F b a = (->) a b
instance Fun (F b)
Related Posts Related Posts :
  • What is the usage of a final var in Scala
  • Define Generic Types with String
  • Why there is a ClassCastException when isInstanceOf returns true on a scala type with wildcard parameter?
  • How to reaload scala application after code change using actors and sbt
  • akka non-blocking BoundedMailbox
  • Why are constructor parameters made into members for case classes?
  • Higher order tail recursive function needs to terminate early
  • How can I reusably filter based on type in Scala?
  • Why does Scala sbt update every time I start it from command prompt?
  • Recommended Scala io library
  • Thread-safely transforming a value in a mutable map
  • Why does chaining match expressions does not compile?
  • Ebean not persisting foreign keys
  • Difference between def m(p: T forSome {type T} and def m1(p:Any), is there any ? Explanation needed based on Scala Langu
  • macro does not find out enclosing vals
  • Spark : how to run spark file from spark shell
  • Flattening a list of lists to a set with exceptions in scala
  • flatMap implementation in Scala
  • Confused about a few lines code in a scala official document page
  • How to input parameters when running bash command with Scala
  • Location header is lost if max-redirects > 1
  • Controller Spec is using FakeApplication, but can't load test configuration
  • Scala code analyzer targets case variable names that are identical to the outer matched varables - "suspicous shado
  • Why does authorize directive execute after the code it's supposed to protect?
  • Scala. Checking if a Type is Comparable
  • Does having a private constructor on a value class negate the benefits of a value class?
  • How to transform submitted json in Play 2.0?
  • Scala warning match may not be exhaustive
  • Pure not a member of objective Promise in PlayFramework
  • How to unmarshal POST params and JSON body in a single route?
  • Spark:How to use join method?
  • is client thread-safe in Twitter Finagle
  • Why is the method accepts only one argument?
  • Scala Play 2.3 Working with gCloud Storage - any libs to go async?
  • spray.io strange get/delete/detach directives behavior
  • SBT cannot resolve class declared in src/main/scala in a src/test/scala test class
  • Configuring actor behavior using typesafe Config and HOCON
  • Scalatra: Migrating Jersey Filters to Scalatra
  • Compilation error when using Scaldi
  • Scalac hanging in phase typer
  • how to have different source code when cross-compiling Scala with sbt? (changes in MurmurHash)
  • How to set different scalacOptions per Scala version when cross-compiling using Build.scala?
  • Possible Bug in JDBC?
  • Is there a Scala compiler flag to warn when tail recursion is applied without annotation?
  • scala case class put methods in companion object?
  • multiproject sbt doesn't generate file structure
  • Scala "multilevel" abstract class / abstract objects replacement
  • Scala, getting the type parameters of a KList as an HList
  • Why does Play refuse form reporting "Cannot resolve method apply with such signature: Missing arguments"?
  • How to split string with trailing empty strings in result?
  • Scala group by list of list and subtracts grouped values
  • Scala - Creating a function to produce Unary string or integer values
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org