How print functions in Haskell like a python or scala? - function

I try to print functions in Haskell only for fun, like this example:
{-# LANGUAGE FlexibleInstances #-}
instance Show (Int -> Bool) where
show _ = "function: Int -> Bool"
loading in GHCi and run and example:
λ> :l foo
[1 of 1] Compiling Main ( foo.hs, interpreted )
foo.hs:2:1: Warning: Unrecognised pragma
Ok, modules loaded: Main.
λ> (==2) :: Int -> Bool
function: Int -> Bool
But, I wish to see that every function print yourself at invocation.

You can not have this for a general function as type information is present only at compile time, but you use Typeable class for writing something close enough if the type is an instance for Typeable class.
import Data.Typeable
instance (Typeable a, Typeable b) => Show (a -> b) where
show f = "Function: " ++ (show $ typeOf f)
Testing this in ghci
*Main> (+)
Function: Integer -> Integer -> Integer
*Main> (+10)
Function: Integer -> Integer
But this will not work for general functions until the type is restricted to a type that has Typeable instance.
*Main> zip
<interactive>:3:1:
Ambiguous type variable `a0' in the constraint:
(Typeable a0) arising from a use of `print'
Probable fix: add a type signature that fixes these type variable(s)
In a stmt of an interactive GHCi command: print it
<interactive>:3:1:
Ambiguous type variable `b0' in the constraint:
(Typeable b0) arising from a use of `print'
Probable fix: add a type signature that fixes these type variable(s)
In a stmt of an interactive GHCi command: print it
*Main> zip :: [Int] -> [Bool] -> [(Int,Bool)]
Function: [Int] -> [Bool] -> [(Int,Bool)]

I'm assuming that you want the show method to print the function's address, which is what Python does:
>>> def foo(a):
... return a
...
>>> print foo
<function foo at 0xb76f679c>
There is really no supported way to do it (Haskell is a safe, high-level language that abstracts from such low-level details as function pointers), unless you're willing to use the internal GHC function unpackClosure#:
{-# LANGUAGE MagicHash,UnboxedTuples,FlexibleInstances #-}
module Main
where
import GHC.Base
import Text.Printf
instance Show (a -> a) where
show f = case unpackClosure# f of
(# a, _, _ #) -> let addr = (I# (addr2Int# a))
in printf "<function ??? at %x>" addr
main :: IO ()
main = print (\a -> a)
Testing:
$ ./Main
<function ??? at 804cf90>
Unfortunately, there is no way to get the function's name, since it is simply not present in the compiled executable (there may be debug information, but you can't count on its presence). If your function is callable from C, you can also get its address by using a C helper.

Related

Implementing functions in Haskell

I'm trying to implement an eval function using my own type aliases and data constructor. This function is supposed to return an updated dictionary Dict and program counter Counter according to the Func inputted. Basically, I want it to increment the counter if an input is correct.
These are my type aliases:
type Counter = Int
type Name = String
type Dict = Map Name Const
This is a type I created to be used in a later the class I mention below:
data Func = GET_INT Int
| GET_DICT Name
| JUMP Counter
deriving Show
And this is the class with the function and where I'm making Func an instance of it:
class Evaluate a where
eval :: Func -> (Dict, Counter) -> Maybe (Dict, Counter)
instance Evaluate Func where
eval (GET_INT a)(d, c) = Just(d, c+1)
eval (GET_DICT a)(d, c) = Just(d, c+1)
eval (JUMP a)(d, c) = Just(d, c+1)
eval = Nothing
However, I am getting some errors. First of all, I am getting the following: Expected a type, but 'Counter' has kind 'Const'
Secondly, I am not sure I entered the correct parameters for the Evaluate class, as a is not being used anywhere. Also, I don't think the inputs for the function will work as they are above.
Can anyone help figure out how to get the function to work?
These are my types:
type Counter = Int
type Name = String
type Dict = Map Name Int
Those are type aliases, but ok.
This is my dataclass:
data Func = GET_INT Int
| GET_DICT Name
deriving Show
The term "dataclass" doesn't mean anything. Func is a type. There are two data constructors. Ok.
And this is the class with the function I'm trying to create:
class Evaluate a where
eval :: a -> (Dict, Counter) -> Maybe (Dict, Counter)
Well that doesn't make much sense. What is eval and why should it be parameterized by a? I think you'd be better served by just defining eval :: Func -> (Dict, Counter) -> Maybe (Dict, Counter) first and thinking hard about why you'd want to make it more polymorphic.
eval (GET_INT a)([(d1, d2)],c) = ([(d1,d2)], c)
eval (GET_DICT a)([(d1, d2)],c) = ([(d1,d2)], c)
This is the error I'm getting: Equations for `eval' have different numbers of arguments.
No. With the code you presented this is not the error. You should always provide the actual code used to produce the error causing your confusion.
Actual error number one:
so.hs:15:20: error:
• Couldn't match type ‘[(a0, b0)]’ with ‘Map Name Int’
Expected type: Dict
Actual type: [(a0, b0)]
• In the pattern: [(d1, d2)]
In the pattern: ([(d1, d2)], c)
In an equation for ‘eval’:
eval (GET_INT a) ([(d1, d2)], c) = ([(d1, d2)], c)
|
15 | eval (GET_INT a)([(d1, d2)],c) = ([(d1,d2)], c)
This is because, with small exception, the syntax [ ... ] is a list and not a Map. You can not pattern match on maps and should just match a variable such as env.
so.hs:15:36: error:
• Couldn't match expected type ‘Maybe (Dict, Counter)’
with actual type ‘([(a0, b0)], Counter)’
• In the expression: ([(d1, d2)], c)
In an equation for ‘eval’:
eval (GET_INT a) ([(d1, d2)], c) = ([(d1, d2)], c)
In the instance declaration for ‘Evaluate Func’
• Relevant bindings include
d2 :: b0 (bound at so.hs:15:26)
d1 :: a0 (bound at so.hs:15:22)
|
15 | eval (GET_INT a)([(d1, d2)],c) = ([(d1,d2)], c)
A tuple of (a,b) is not the same as Maybe (a,b). Sadly you evidently already knew this but pasted distracting code - clean up the code prior to asking the question.
If we fix these two issues then we get code that loads fine but is entirely worthless:
import Data.Map
type Counter = Int
type Name = String
type Dict = Map Name Int
data Func = GET_INT Int
| GET_DICT Name
deriving Show
class Evaluate a where
eval :: a -> (Dict, Counter) -> Maybe (Dict, Counter)
instance Evaluate Func where
eval (GET_INT a) (env,c) = Just (env, c)
eval (GET_DICT a) (env,c) = Just (env, c)

How to handle variability of JSON objects in Haskell?

Some REST service has variable returning JSONs, for example some fields can appear or disappear depending on the parameters of the request, the structure itself may change, nesting, etc.
So, this leads to avalanche-type growth in the number of types (along with FromJSON instances). Options are to:
try to make a lot of fields under Maybe (but this does not help very much with the variability in structure)
to introduce a lot of types
to create different phantom types (actually no big difference with prev.)
The 1. has drawback that if your call with some fixed parameters always returns good knows fields, you have to handle Nothing cases too, code becomes more complex. The 2. and 3. is tiring.
What is the most simple/convenient way to handle such variability in Haskell (if you use Aeson, sure, another option is to avoid Aeson usage)?
A possible solution to the existing/non-existing fields problem using type-level computation.
Some required extensions and imports:
{-# LANGUAGE DeriveGeneric, ScopedTypeVariables, DataKinds, KindSignatures,
TypeApplications, TypeFamilies, TypeOperators, FlexibleContexts #-}
import Data.Aeson
import Data.Proxy
import GHC.Generics
import GHC.TypeLits
Here's a data type (to be used promoted) that indicates if some field is absent or present. Also a type family that maps absent types to ():
data Presence = Present
| Absent
type family Encode p v :: * where
Encode Present v = v
Encode Absent v = ()
Now we can define a parameterized record containing all possible fields, like this:
data Foo (a :: Presence)
(b :: Presence)
(c :: Presence) = Foo {
field1 :: Encode a Int,
field2 :: Encode b Bool,
field3 :: Encode c Char
} deriving Generic
instance (FromJSON (Encode a Int),
FromJSON (Encode b Bool),
FromJSON (Encode c Char)) => FromJSON (Foo a b c)
One problem: writing the full type for each combination of occurrences/absences would be tedious, especially if only a few fields are present each time. But perhaps we could define an auxiliary type synonym FooWith that let us mention only those fields that are present:
type family Mentioned (ns :: [Symbol]) (n :: Symbol) :: Presence where
Mentioned '[] _ = Absent
Mentioned (n ': _) n = Present
Mentioned (_ ': ns) n = Mentioned ns n
-- the field names are repeated as symbols, how to avoid this?
type FooWith (ns :: [Symbol]) = Foo (Mentioned ns "field1")
(Mentioned ns "field2")
(Mentioned ns "field3")
Example of use:
ghci> :kind! FooWith '["field2","field3"]
FooWith '["field2","field3"] :: * = Foo 'Absent 'Present 'Present
Another problem: for each request, we must repeat the list of required fields two times: one in the URL ("fields=a,b,c...") and another in the expected type. It would be better to have a single source of truth.
We can deduce the term-level list of fields to be added to the URL from the type-level list of fields, by using an auxiliary type class Demote:
class Demote (ns :: [Symbol]) where
demote :: Proxy ns -> [String]
instance Demote '[] where
demote _ = []
instance (KnownSymbol n, Demote ns) => Demote (n ': ns) where
demote _ = symbolVal (Proxy #n) : demote (Proxy #ns)
For example:
ghci> demote (Proxy #["field2","field3"])
["field2","field3"]

Recursively change a JSON data structure in Haskell

I am trying to write a function that will take a JSON object, make a change to every string value in it and return a new JSON object. So far my code is:
applyContext :: FromJSON a => a -> a
applyContext x =
case x of
Array _ -> map applyContext x
Object _ -> map applyContext x
String _ -> parseValue x
_ -> x
However, the compiler complains about second second case line:
Couldn't match expected type `[b0]' with actual type `a'
`a' is a rigid type variable bound by
the type signature for:
applyContext :: forall a. FromJSON a => a -> a
at app\Main.hs:43:17
I'm guessing that is because map is meant to work on lists, but I would have naively expected it to use Data.HashMap.Lazy.map instead, since that is what the type actually is in that case. If I explicitly use that function I get
Couldn't match expected type `HashMap.HashMap k0 v20' with actual type `a'
which also makes sense, since I haven't constrained a to that extent because then it wouldn't work for the other cases. I suspect that if I throw enough explicit types at this I could make it work but it feels like it should be a lot simpler. What is an idiomatic way of writing this function, or if this is good then what would be the simplest way of getting the types right?
First of all, what FromJSON a => a does mean? It's type of some thing what says: it can be thing with any type but only from class FromJSON. This class can contain types which very differently constructed and you can't do any pattern matching. You can only do what is specified in the class FromJSON declaration by programmer. Basically, there is one method parseJSON :: FromJSON a => Value -> Parser a.
Secondly, you should use some isomorphic representation of JSON for your work. The type Value is good one. So, you can do the main work by the function like Value -> Value. After that, you can compose this fuction with parseJSON and toJSON for generalse types.
Like this:
change :: Value -> Value
change (Array x) = Array . fmap change $ x
change (Object x) = Object . fmap change $ x
change (String x) = Object . parseValue $ x
change x = x
apply :: (ToJSON a, FromJSON b) => (Value -> Value) -> a -> Result b
apply change = fromJSON . change . toJSON
unsafeApply :: (ToJSON a, FromJSON b) => (Value -> Value) -> a -> b
unsafeApply change x = case apply change x of
Success x -> x
Error msg -> error $ "unsafeApply: " ++ msg
applyContext :: (ToJSON a, FromJSON b) => a -> b
applyContext = unsafeApply change
You can write more complicated transformations like Value -> Value with lens and lens-aeson. For example:
import Control.Lens
import Control.Monad.State
import Data.Aeson
import Data.Aeson.Lens
import Data.Text.Lens
import Data.Char
change :: Value -> Value
change = execState go
where
go = do
zoom values go
zoom members go
_String . _Text . each %= toUpper
_Bool %= not
_Number *= 10
main = print $ json & _Value %~ change
where json = "{\"a\":[1,\"foo\",false],\"b\":\"bar\",\"c\":{\"d\":5}}"
Output will be:
"{\"a\":[10,\"FOO\",true],\"b\":\"BAR\",\"c\":{\"d\":50}}"

Int and Num type of haskell

I have below code to take the args to set some offset time.
setOffsetTime :: (Ord a, Num b)=>[a] -> b
setOffsetTime [] = 200
setOffsetTime (x:xs) = read x::Int
But compiler says "Could not deduce (b ~ Int) from the context (Ord a, Num b) bound by the type signature for setOffsetTime :: (Ord a, Num b) => [a] -> b
Also I found I could not use 200.0 if I want float as the default value. The compilers says "Could not deduce (Fractional b) arising from the literal `200.0'"
Could any one show me some code as a function (not in the prelude) that takes an arg to store some variable so I can use in other function? I can do this in the main = do, but hope
to use an elegant function to achieve this.
Is there any global constant stuff in Hasekll? I googled it, but seems not.
I wanna use Haskell to replace some of my python script although it is not easy.
I think this type signature doesn't quite mean what you think it does:
setOffsetTime :: (Ord a, Num b)=>[a] -> b
What that says is "if you give me a value of type [a], for any type a you choose that is a member of the Ord type class, I will give you a value of type b, for any type b that you choose that is a member of the Num type class". The caller gets to pick the particular types a and b that are used each time setOffsetTime is called.
So trying to return a value of type Int (or Float, or any particular type) doesn't make sense. Int is indeed a member of the type class Num, but it's not any member of the type class Num. According to that type signature, I should be able to make a brand new instance of Num that you've never seen before, import setOffsetTime from your module, and call it to get a value of my new type.
To come up with an acceptable return value, you can only use functions that likewise return an arbitrary Num. You can't use any functions of particular concrete types.
Existential types are essentially a mechanism for allowing the callee to choose the value for a type variable (and then the caller has to be written to work regardless of what that type is), but that's not really something you want to be getting into while you're still learning.
If you are convinced that the implementation of your function is correct, i.e., that it should interpret the first element in its input list as the number to return and return 200 if there is no such argument, then you only need to make sure that the type signature matches that implementation (which it does not do, right now).
To do so, you could, for example, remove the type signature and ask ghci to infer the type:
$ ghci
GHCi, version 7.6.2: http://www.haskell.org/ghc/ :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer-gmp ... linking ... done.
Loading package base ... linking ... done.
Prelude> :{
Prelude| let setOffsetTime [] = 200
Prelude| setOffsetTime (x : xs) = read x :: Int
Prelude| :}
Prelude> :t setOffsetTime
setOffsetTime :: [String] -> Int
Prelude> :q
Leaving GHCi.
$
And indeed,
setOffsetTime :: [String] -> Int
setOffsetTime [] = 200
setOffsetTime (x : xs) = read x :: Int
compiles fine.
If you want a slightly more general type, you can drop the ascription :: Int from the second case. The above method then tells you that you can write
setOffsetTime :: (Num a, Read a) => [String] -> a
setOffsetTime [] = 200
setOffsetTime (x : xs) = read x
From the comment that you added to your question, I understand that you want your function to return a floating-point number. In that case, you can write
setOffsetTime :: [String] -> Float
setOffsetTime [] = 200.0
setOffsetTime (x : xs) = read x
or, more general:
setOffsetTime :: (Fractional a, Read a) => [String] -> a
setOffsetTime [] = 200.0
setOffsetTime (x : xs) = read x

How to make a IO (a->b) function from a -> IO b in Haskell

I want to write a function that can list a directory recursively in breadth-first in Haskell.
As you can see I need a function that can convert a (a -> IO b) to a IO (a->b). Simple as it seems, I can't make it. And I want to know how to do or whether it is possible.
dirElem :: FilePath -> IO [FilePath]
dirElem dirPath = do
getDirectoryContents'' <- theConvert getDirectoryContents'
return $ takeWhile (not.null) $ iterate (concatMap getDirectoryContents'') [dirPath] where
getDirectoryContents' dirPath = do
isDir <- do doesDirectoryExist dirPath
if isDir then dirContent else return [] where
dirContent = do
contents <- getDirectoryContents dirPath
return.(map (dirElem</>)).tail.tail contents
theConvert :: (a -> IO b) -> IO (a -> b)
theConvert = ??????????
This cannot be done. The reason is that the function can use its argument of type a to determine what IO action is executed. Consider
action :: Bool -> IO String
action True = putStrLn "Enter something:" >> getLine
action False = exitFailure
Now if you'd convert it somehow to IO (Bool -> String) and evaluate this action, what should happen? There is no solution. We cannot decide if we should read a string or exit, because we don't know the Bool argument yet (and we may never know it, if the resulting function isn't called on an argument).
John's answer is a bad idea. It simply lets the IO action escape into pure computations, which will make your life miserable and you'll lose Haskell's referential transparency! For example running:
main = unsafe action >> return ()
will do nothing even though the IO action was called. Moreover, if we modify it a bit:
main = do
f <- unsafe action
putStrLn "The action has been called, calling its pure output function."
putStrLn $ "The result is: " ++ f True
you'll see that the action that asks for an input is executed in a pure computation, inside calling f. You'll have no guarantee when (if at all) the action is executed!
Edit: As others pointed out, it isn't specific just to IO. For example, if the monad were Maybe, you couldn't implement (a -> Maybe b) -> Maybe (a -> b). Or for Either, you couldn't implement (a -> Either c b) -> Either c (a -> b). The key is always that for a -> m b we can choose different effects depending on a, while in m (a -> b) the effect must be fixed.
You cannot do it in a pure way in general, but if you can enumerate all the argument values you can perform all the IO upfront and return a pure function. Something like
cacheForArgs :: [a] -> (a -> IO b) -> IO (a -> b)
cacheForArgs as f = do
bs <- mapM f as
let abs = zip as bs
return $ \ a -> fromMaybe (error "argument not cached") $ lookup a abs
cacheBounded :: (Enum a, Bounded a) => (a -> IO b) -> IO (a -> b)
cacheBounded = cacheForArgs [minBound .. maxBound]
But this function doesn't really help you much in your use case.
You cannot create such function in a safe manner. Say we have f :: a -> IO b and g = theConvert f :: IO (a -> b). They are two very different functions f is an function that takes an argument of type a and returns an IO action with result b, where the io-action may depend on the argument given. g on the other hand is an IO action with as result a function a->b, the io-action cannot depend on any argument.
Now to illustrate this problem lets lookat
theConvert putStr :: IO (String -> ())
Now what should it do when its run, it can certainly not print a given argument as it has no argument. Thus unlike putStr it can only do one action and then return some function of type String -> (), which has only one option const () (assuming no use of error or undefined).
Just as a side not, the other way around can be done, it adds the notion that the resulting action depends on the argument, while it actually does not. It can be written as
theOtherConvert :: IO (a -> b) -> (a -> IO b)
theOtherConvert m x = m >>= \f -> return $ f x
Though it works on any monad, or in applicative form theOtherConvert m x = m <*> pure x.
Petr Pudlák's answer is excellent, but I feel it can be generalized by abstracting away from IO, and looking at it from the point of view of the Applicative and Monad type classes.
Consider the types of the "combining" operations from Applicative and Monad:
(<*>) :: Applicative m => m (a -> b) -> m a -> m b
(>>=) :: Monad m => m a -> (a -> m b) -> m b
So you could say that your type a -> IO b is "monadic" while IO (a -> b) is "applicative"—meaning that you need monadic operations to compose types that look like a -> IO b, but only applicative operations for IO (a -> b)
There's a well-known intuitive statement of the "power" difference between Monad and Applicative:
Applicative computations have a fixed static structure; what actions will be executed, what order they will be executed in, and the manner in which the results will be combined is known ahead of time.
Monadic computations don't have such a fixed static structure; a monadic computation can examine the result value from one of its subactions and then choose between different structures at execution time.
Petr's answer is a concrete illustration of this point. I'll repeat his definition of action:
action :: Bool -> IO String
action True = putStrLn "Enter something:" >> getLine
action False = exitFailure
Suppose we have foo :: IO Bool. Then when we write foo >>= action to bind action's parameter to foo's result, the resulting computation does nothing less than what my second bullet point describes; it examines the result of executing foo and chooses between alternative actions based on its value. This is precisely one of the things that Monad allows you to do that Applicative doesn't. You can't Petr's action into IO (Bool -> String) unless at the same time you predetermine which branch would be taken.
Similar remarks apply to augustss's response. By requiring that a list of values be specified ahead of time, what it's doing is making you choose which branches to take ahead of time, taking them all, and then allowing you to pick between their results.