Do infix functions in Haskell have type expressions ? - haskell

For example, ++is essentially a function. I would expect that when I type :t ++ or :t prefixName that I would obtain a type expression, but I receive a parse error. Is there a prefix for ++ or is there a special method to call :t for infix functions.

Yes, the infix functions are functions, but to use them with :t you need to write it as a normal prefix function:
:t (++)
which gives
(++) :: [a] -> [a] -> [a]
This is part of the haskell syntax. To convert an infix function to prefix, surround it by parens, e.g.,
(+) 1 2
is equivalent to
1 + 2
Conversely, a normal prefix function can be used infix by surrounding it
with backticks, e.g.,
reverse `map` ["hello","world"]
is the same as
map reverse ["hello","world"]

Related

Why is (.) called infix as just . rather than `(.)`

I learned that functions can be invoked in two ways; prefix and infix. For example, say I've created this function:
example :: [Char] -> [Char] -> [Char]
example x y = x ++ " " ++ y
I can call it prefix like so:
example "Hello" "World"
or infix like so:
"Hello" `example` "World"
Both of which will result in the list of chars representing a string "Hello World".
However, I am now learning about function composition, and have come across the function defined like so:
(.) :: (b -> c) -> (a -> b) -> a -> c
So, say I was wanting to compose negate with multiplication by three. I would write the prefix invocation like:
negateComposedWithMultByThree = (.) negate (*3)
And the infix invocation like:
negateComposedWithMultByThree = negate `(.)` (*3)
But, whilst the prefix invocation compiles, the infix invocation does not and instead gives me the error message:
error: parse error on input `('
It seems, in order to call compose infix, I need to omit the brackets and call it like so:
negateComposedWithMultByThree = negate . (*3)
Can anyone shed any light on this? Why does "Hello" `example` "World" whilst negate `(.)` (*3) does not?
In addition, if I try to make my own function with a signature like this:
(,) :: Int -> Int
(,) x = 1
It does not compile, with the error:
"Invalid type signature (,) : ... Should be of form :: "
There's nothing deep here. There's just two kinds of identifiers that have different rules about how they're parsed: by-default-infix, and by-default-prefix. You can tell which is which, because by-default-infix identifiers contain only punctuation, while by-default-prefix identifiers contain only numbers, letters, apostrophes, and underscores.
Recognizing that the default isn't always the right choice, the language provides conversions away from the default behavior. So there are two separate syntax rules, one that converts a by-default-infix identifier to prefix (add parentheses), and one that converts a by-default-prefix identifier to infix (add backticks). You can not nest these conversions: a by-default-infix identifier converted to prefix form is not a by-default-prefix identifier.
That's it. Nothing fundamentally interesting -- all of them become just function applications once parsed -- it's just syntax sugar.

Haskell Uncurrying for Multiple Arguments [duplicate]

In Python and Ruby (and others as well, I'm sure). you can prefix an enumerable with * ("splat") to use it as an argument list. For instance, in Python:
>>> def foo(a,b): return a + b
>>> foo(1,2)
3
>>> tup = (1,2)
>>> foo(*tup)
3
Is there something similar in Haskell? I assume it wouldn't work on lists due to their arbitrary length, but I feel that with tuples it ought to work. Here's an example of what I'd like:
ghci> let f a b = a + b
ghci> :t f
f :: Num a => a -> a -> a
ghci> f 1 2
3
ghci> let tuple = (1,2)
I'm looking for an operator (or function) that allows me to do:
ghci> f `op` tuple
3
I have seen (<*>) being called "splat", but it doesn't seem to be referring to the same thing as splat in other languages. I tried it anyway:
ghci> import Control.Applicative
ghci> f <*> tuple
<interactive>:1:7:
Couldn't match expected type `b0 -> b0'
with actual type `(Integer, Integer)'
In the second argument of `(<*>)', namely `tuple'
In the expression: f <*> tuple
In an equation for `it': it = f <*> tuple
Yes, you can apply functions to tuples, using the tuple package. Check out, in particular, the uncurryN function, which handles up to 32-tuples:
Prelude Data.Tuple.Curry> (+) `uncurryN` (1, 2)
3
The uncurry function turns a function on two arguments into a function on a tuple. Lists would not work in general because of their requirement for homogeneity.
No, Haskell's type system doesn't like that. Check this similar question for more details:
How do I define Lisp’s apply in Haskell?
BTW, the splat operator you talk about is also known as the apply function, commonly found on dynamical functional languages (like LISP and Javascript).

printing a list of type signatures

I want to be able to type the following in ghci:
map showTypeSignature [(+),(-),show]
I want ghci to return the following list of Strings:
["(+) :: Num a => a -> a -> a","(-) :: Num a => a -> a -> a","show :: Show a => a -> String"]
Naturally, the first place that I run into trouble is that I cannot construct the first list, as the type signatures of the functions don't match. What can I do to construct such a list? How does ghci accomplish the printing of type signatures? Where is the ghci command :t defined (its source)?
What you're asking for isn't really possible. You cannot easily determine the type signature of a Haskell term from within Haskell. At run-time, there's hardly any type information available. The GHCi command :t is a GHCi command, not an interpreted Haskell function, for a reason.
To do something that comes close to what you want you'll have to use GHC itself, as a library. GHC offers the GHC API for such purposes. But then you'll not be able to use arbitrary Haskell terms, but will have to start with a String representation of your terms. Also, invoking the compiler at run-time will necessarily produce an IO output.
kosmikus is right, this doesn't really work out. And shouldn't, the static type system is one of Haskell's most distinguishing features!
However, you can emulate this for monomorphic functions quite well using the Dynamic existential:
showTypeSignature :: Dynamic -> String
showTypeSignature = show . dynTypeRep
Prelude Data.Dynamic> map showTypeSignature [toDyn (+), toDyn (-), toDyn (show)]
["Integer -> Integer -> Integer","Integer -> Integer -> Integer","() -> [Char]"]
As you see ghci had to boil the functions down to monomorphic type here for this to work, which particularly for show is patently useless.
The answers you have about why you can't do this are very good, but there may be another option. If you don't care about getting a Haskell list, and just want to see the types of a bunch of things, you can define a custom GHCi command, say :ts, that shows you the types of a list of things; to wit,
Prelude> :ts (+) (-) show
(+) :: Num a => a -> a -> a
(-) :: Num a => a -> a -> a
show :: Show a => a -> String
To do this, we use :def; :def NAME EXPR, where NAME is an identifier and EXPR is a Haskell expression of type String -> IO String, defines the GHCi command :NAME. Running :NAME ARGS evaluates EXPR ARGS to produce a string, and then runs the resulting string in GHCi. This is less confusing than it sounds. Here's what we do:
Prelude> :def ts return . unlines . map (":type " ++) . words
Prelude> :ts (+) (-) show
(+) :: Num a => a -> a -> a
(-) :: Num a => a -> a -> a
show :: Show a => a -> String
What's going on? This defines :ts to evaluate return . unlines . map (":t " ++) . words, which does the following:
words: Takes a string and splits it on whitespace; e.g., "(+) (-) show" becomes ["(+)", "(-)", "show"].
map (":type " ++): Takes each of the words from before and prepends ":type "; e.g., ["(+)", "(-)", "show"] becomes [":type (+)", ":type (-)", ":type show"]. Notice that we now have a list of GHCi commands.
unlines: Takes a list of strings and puts newlines after each one; e.g., [":type (+)", ":type (-)", ":type show"] becomes ":type (+)\n:type (-)\n:type show\n". Notice that if we pasted this string into GHCi, it would produce the type signatures we want.
return: Lifts a String to an IO String, because that's the type we need.
Thus, :ts name₁ name₂ ... nameₙ will evaluate :type name₁, :type name₂, …, :type nameₙ in succession and prints out the results. Again, you can't get a real list this way, but if you just want to see the types, this will work.

How do I get the type signature of the range function in Haskell?

Many functions in Haskell made up of special characters in Haskell are infix functions. These include *, +, ==, /, etc. To get the type signatures of such functions you put the function in parentheses and execute :t, like so:
GHCi> :t (==)
(==) :: Eq a => a -> a -> Bool
I wanted to try and get the type signature of the range function, [a..a], but it seems that this function is infix, but can only be used within a list []. I tried all the following, but none worked:
GHCi> :t (..)
<interactive>:1:2: parse error on input `..'
GHCi> :t ([..])
<interactive>:1:3: parse error on input `..'
GHCi> :t [..]
<interactive>:1:2: parse error on input `..'
GHCi> :t ..
<interactive>:1:1: parse error on input `..'
Does anyone know how to get the type signature of the range function?
The .. is not a function, it's actually syntax sugar. It gets translated to one of several functions: enumFrom, enumFromThen, enumFromTo or enumFromThenTo.
It can't be a normal function because it has four forms that work in different ways. That is, all four of these are valid:
[1..] -- enumFrom 1
[1,2..] -- enumFromThen 1 2
[1..10] -- enumFromTo 1 10
[1,2..10] -- enumFromThenTo 1 2 10
These forms use the four functions I mentioned respectively.
If it was just a normal operator, 1.. would give you a partially applied function; instead, it produces a list. Moreover, for a normal function, the [1,2..10] notation would be parsed as [1,(2..10)] where in reality it all gets turned into a single function taking all three numbers as arguments.
These functions are all part of the Enum class, so the .. notation works for any type that is part of it. For example, you could write [False ..] and get the list [False, True]. (Unfortunately, due to current parsing ambiguities, you can't write [False..] because it then assumes False is a module.)
Try using a lambda.
> :t \x y -> [x..y]
The notation is just syntactic sugar for enumFrom and enumFromTo so it doesn't really have a conventional type.

Does Haskell have a splat operator like Python and Ruby?

In Python and Ruby (and others as well, I'm sure). you can prefix an enumerable with * ("splat") to use it as an argument list. For instance, in Python:
>>> def foo(a,b): return a + b
>>> foo(1,2)
3
>>> tup = (1,2)
>>> foo(*tup)
3
Is there something similar in Haskell? I assume it wouldn't work on lists due to their arbitrary length, but I feel that with tuples it ought to work. Here's an example of what I'd like:
ghci> let f a b = a + b
ghci> :t f
f :: Num a => a -> a -> a
ghci> f 1 2
3
ghci> let tuple = (1,2)
I'm looking for an operator (or function) that allows me to do:
ghci> f `op` tuple
3
I have seen (<*>) being called "splat", but it doesn't seem to be referring to the same thing as splat in other languages. I tried it anyway:
ghci> import Control.Applicative
ghci> f <*> tuple
<interactive>:1:7:
Couldn't match expected type `b0 -> b0'
with actual type `(Integer, Integer)'
In the second argument of `(<*>)', namely `tuple'
In the expression: f <*> tuple
In an equation for `it': it = f <*> tuple
Yes, you can apply functions to tuples, using the tuple package. Check out, in particular, the uncurryN function, which handles up to 32-tuples:
Prelude Data.Tuple.Curry> (+) `uncurryN` (1, 2)
3
The uncurry function turns a function on two arguments into a function on a tuple. Lists would not work in general because of their requirement for homogeneity.
No, Haskell's type system doesn't like that. Check this similar question for more details:
How do I define Lisp’s apply in Haskell?
BTW, the splat operator you talk about is also known as the apply function, commonly found on dynamical functional languages (like LISP and Javascript).

Resources