Scala: normal functions vs tupled functions? - function

What's the difference between these? I know that their type signatures are different, and that all functions start off normal and have to be .tupled to get their tupled form. What's the advantage of using un-tupled (but non-curried) functions? Especially because it seems to me that passing multiple arguments to a tupled function automagically unpacks them anyway, so by all appearances they are the same.
One difference i see is that it forces you to have types for every number of function arguments: Function0, Function1, Function2, Function3 etc, whereas tupled functions are all just Function1[A, R], but that seems like a downside. What's the big advantage of using non-tupled functions that they're the default?

Tupled functions require that a tuple object be created when they are called (unless the arguments happen to already be packed into a tuple). Non-tupled functions simply define a method that takes the appropriate number of arguments. Thus, given the JVM architecture, non-tupled functions are more efficient.

Consider this example:
scala> def mult = (x: Int, y: Int) => x * y
mult: (Int, Int) => Int
scala> val list = List(1, 2, 3)
list: List[Int] = List(1, 2, 3)
scala> list zip list map mult
<console>:10: error: type mismatch;
found : (Int, Int) => Int
required: ((Int, Int)) => ?
list zip list map mult
^
scala> list zip list map mult.tupled
res4: List[Int] = List(1, 4, 9)
There are many situations where you end up pairing elements in tuples. In such situations, you need a tupled function to handle it. But there are many other places where that is not true! For example:
scala> list.foldLeft(1)(mult)
res5: Int = 6
scala> list.foldLeft(1)(mult.tupled)
<console>:10: error: type mismatch;
found : ((Int, Int)) => Int
required: (Int, Int) => Int
list.foldLeft(1)(mult.tupled)
^
So, basically, Scala has a dichotomy between tuples and parameters, which means you have to convert functions from tupled to untupled and vice versa here and there.

Related

How do I find the index of a particular element within a List in DAML?

Say I have a List that looks like this:
let identifiers = ["ABC123", "DEF456", "GHI789"]
I want to know the index if the element "DEF456". What's the recommended way to accomplish this?
In daml 1.2 you can use the elemIndex : Eq a => a -> [a] -> Optional Int function in the DA.List standard library module like so:
daml 1.2 module MyModule where
import DA.List
indexOfElement = scenario do
let identifiers = ["ABC123", "DEF456", "GHI789"]
index : Optional Int = elemIndex "DEF456" identifiers
assert $ index == Some 1
return index
The findIndex function in the Base.List module in the standard library, does what you want.
daml 1.0 module FindIndex where
import Base.List
import Base.Maybe
test foo : Scenario {} = scenario
let
identifiers = ["ABC123", "DEF456", "GHI789"]
index: Maybe Integer = findIndex ((==) "DEF456") identifiers
assert $ index == Just 1
Under the hood most list manipulation in DAML, including findIndex is implemented using foldr and foldl.
-- Returns the index of the first element in the list satisfying the predicate, or M.Nothing if there is no such element.
def findIndex (f: a -> Bool) (xs: List a) : Maybe Integer =
headMay (findIndices f xs)
-- Returns the indices of all elements satisfying the predicate, in ascending order.
def findIndices (f: a -> Bool) (xs: List a) =
let work acc x =
let i = fst acc
let is = snd acc
tuple (i + 1) (if f x then cons i is else is)
reverse (snd (foldl work (tuple 0 nil) xs))

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"]

What are advantages of ApplicativeBuilder?

Applicative provides "operator" <*>, which I can use as follows:
val f: (Int, Int) => Int = {(x, y) => x + y}
1.some <*> (2.some <*> f.curried.some)
In addition to that scalaz provides ApplicativeBuilder:
(1.some |#| 2.some)(f)
What are advantages of ApplicativeBuilder ? When would you use |#| instead of <*> ?
Better type inference
scala> ^(1.right[String], 2.right[String])(_ + _)
<console>:16: error: type mismatch;
found : scalaz.\/[String,Int]
required: ?F[?A]
Note that implicit conversions are not applicable because they are ambiguous:
both method ToAssociativeOps in trait ToAssociativeOps of type [F[_, _], A, B](v: F[A,B])(implicit F0: scalaz.Associative[F])scalaz.syntax.AssociativeOps[F,A,B]
and method ToBitraverseOps in trait ToBitraverseOps of type [F[_, _], A, B](v: F[A,B])(implicit F0: scalaz.Bitraverse[F])scalaz.syntax.BitraverseOps[F,A,B]
are possible conversion functions from scalaz.\/[String,Int] to ?F[?A]
^(1.right[String], 2.right[String])(_ + _)
^
scala> (1.right[String] |#| 2.right[String])(_ + _)
res1: scalaz.\/[String,Int] = \/-(3)
There are not really advantages of one over the other, but as you can see the Applicative Builder does not require, that your function is curried and in the context of F. In my opinion it also has a more approachable usage of brackets.
You could also say that the Applicative Builder builds temporary objects, so that you should probably avoid it, when using in very performance critical code and/or loops. In this case you could use another alternative like: Applicative[Option].apply2(3.some, 4.some)(f). This is again very close to the |#| syntax, only that you do not have to count the number of parameters you want to provide for f(n1, n2, ...).

Why are types of a named function different from an anonymous one in scala [duplicate]

This question already has answers here:
Difference between method and function in Scala
(12 answers)
Closed 9 years ago.
In scala, a named function is defined as:
scala> def addOne(x: Int): Int = x+1
addOne: (x: Int)Int
scala> :type addOne
(x: Int)Int
And an anonymous one as:
scala> val addOne = (x:Int) => x+1
addOne: Int => Int = <function1>
scala> :type addOne
Int => Int
Why do their types look different?
Why can't a named function be passed as an argument to another function?
Shouldn't both be treated uniformly from type and first-order behavior point of views?
def addOne(x: Int): Int is not a function in scala. It's a method of some object.
Functions like val addOne = (x:Int) => x+1 are objects of type FunctionN (in this case Function1) with method apply.
One can use method as function in scala - compiler can create a function from method, for instance:
scala> List(1, 2, 3).map((1).+) // or just `1+`
res0: List[Int] = List(2, 3, 4)
In this case method + of object 1 is used as function x => (1).+(x).
scala> List(1, 2, 3).foreach(println)
1
2
3
Method println of object Predef is used as function s => Predef.println(s).
Since version 2.10 you can't use :type on methods:
scala> def addOne(x: Int): Int = x+1
addOne: (x: Int)Int
scala> :type addOne
<console>:9: error: missing arguments for method addOne;
follow this method with `_' if you want to treat it as a partially applied function
addOne
^

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