Purescript - Cannot unify type - purescript

I am new to Purescript (as well as Haskell) and I am stuck with a cannot unify error.
Initially I had:
newtype Domain = Domain String
newtype Keyword = Keyword String
type Result = {
domain :: Domain,
occurred :: Boolean,
position :: Number,
quality :: Number
}
is_min_pos :: Maybe Result -> Maybe Result -> Maybe Result
is_min_pos Nothing Nothing = Nothing
is_min_pos Nothing y = y
is_min_pos x Nothing = x
is_min_pos x y = if y.position < x.position then y else x
This was giving me the error
Cannot unify type
Prim.Object
with type
Data.Maybe.Maybe
I assumed it was because it was expecting x and y to be of type Maybe Record. So to be explicit I changed the code to, to pattern match by type.
data Result = Result {
domain :: Domain,
occurred :: Boolean,
position :: Number,
quality :: Number
}
is_min_pos (Result x) (Result y) = if y.position < x.position then y else x
Now I get the error
Cannot unify type
Data.Maybe.Maybe Processor.Result
with type
Processor.Result
And this refers to this section
y.position < x.position -- in the first case
and in the second case
Result x -- on the pattern matching side
I am working on it further
type Results = List Result
get_item_with_min_position :: Results -> Maybe Result
--get_item_with_min_position [] = Nothing
get_item_with_min_position results = foldl is_min_pos Nothing results
I am using 'foldl' from Foldable. I am not sure how to pattern match an empty list. If I could, I would change the type signature to
is_min_pos :: Maybe Result -> Result -> Maybe Result
I now get the error
Cannot unify type
Prim.Object
with type
Data.Maybe.Maybe
It is understandable because in
foldl is_min_pos Nothing results
results is of type List Result
is_min_pos expects Maybe Result
What would be a clean way to solve this?

The Maybe type has two data constructors: Nothing, which you are correctly matching, and Just. If you want to match something of type Maybe a which does contain a value, you should match the Just constructor.
You need to modify the final case as follows:
is_min_pos (Just x) (Just y) = if y.position < x.position
then Just y
else Just x
Here, Just x has the type Maybe Result, which is correct according to the type signature, and so x has type Result, so you can use the .position accessor to read its position property.

Related

How to check if a value exists in a list in smlnj

I'm working on some homework and I need to create a function that checks if a value exists in a list. If it does it will return true, otherwise it returns false. I have an idea of how to do it but I keep getting errors. I think it may be due to my lack of knowledge of syntax and style as this is my first time coding in sml.
I created the function exist and am passing a value and list in as a tuple.
fun exist (x, []) =
if x = hd ([]) then true
else if x = tl ([]) then true
else false;
Sorry if this code is laughably incorrect but I get the error message:
" stdIn:2.6 Warning: calling polyEqual
stdIn:3.11 Warning: calling polyEqual
stdIn:1.6-4.11 Warning: match nonexhaustive
(x,nil) => ...
val exist = fn : ''a list * 'b list -> bool "
and I'm not really sure how to fix this. Any help would be great.
Your function is pattern-matching on [], so it can only ever match the empty list.
Also, hd [] and tl [] are both errors since the empty list has neither head nor tail.
Further, if some_condition then true else false is equivalent to some_condition.
(And if some_condition then false else true is equivalent to not some_condition.)
Logical expressions are usually more readable than chains of conditionals.
And you forgot to recurse; you need to use exist on the tail of the list if the first element is not what you're looking for.
Either stick to pattern matching:
fun exist (_, []) = false
| exist (x, y::ys) = x = y orelse exist (x, ys)
or don't use it:
fun exist (x, xs) = not (null xs) andalso (x = hd xs orelse exist (x, tl xs))
Pattern matching is often the most readable solution and gives a clear picture of the various cases.
(You seem to have mixed the two forms, treating [] as an identifier rather than a type constructor.)

Similar record types in a list/array in purescript

Is there any way to do something like
first = {x:0}
second = {x:1,y:1}
both = [first, second]
such that both is inferred as {x::Int | r} or something like that?
I've tried a few things:
[{x:3}] :: Array(forall r. {x::Int|r}) -- nope
test = Nil :: List(forall r. {x::Int|r})
{x:1} : test -- nope
type X r = {x::Int | r}
test = Nil :: List(X) -- nope
test = Nil :: List(X())
{x:1} : test
{x:1, y:1} : test -- nope
Everything I can think of seems to tell me that combining records like this into a collection is not supported. Kind of like, a function can be polymorphic but a list cannot. Is that the correct interpretation? It reminds me a bit of the F# "value restriction" problem, though I thought that was just because of CLR restrictions whereas JS should not have that issue. But maybe it's unrelated.
Is there any way to declare the list/array to support this?
What you're looking for is "existential types", and PureScript just doesn't support those at the syntax level the way Haskell does. But you can roll your own :-)
One way to go is "data abstraction" - i.e. encode the data in terms of operations you'll want to perform on it. For example, let's say you'll want to get the value of x out of them at some point. In that case, make an array of these:
type RecordRep = Unit -> Int
toRecordRep :: forall r. { x :: Int | r } -> RecordRep
toRecordRep {x} _ = x
-- Construct the array using `toRecordRep`
test :: Array RecordRep
test = [ toRecordRep {x:1}, toRecordRep {x:1, y:1} ]
-- Later use the operation
allTheXs :: Array Int
allTheXs = test <#> \r -> r unit
If you have multiple such operations, you can always make a record of them:
type RecordRep =
{ getX :: Unit -> Int
, show :: Unit -> String
, toJavaScript :: Unit -> Foreign.Object
}
toRecordRep r =
{ getX: const r.x
, show: const $ show r.x
, toJavaScript: const $ unsafeCoerce r
}
(note the Unit arguments in every function - they're there for the laziness, assuming each operation could be expensive)
But if you really need the type machinery, you can do what I call "poor man's existential type". If you look closely, existential types are nothing more than "deferred" type checks - deferred to the point where you'll need to see the type. And what's a mechanism to defer something in an ML language? That's right - a function! :-)
newtype RecordRep = RecordRep (forall a. (forall r. {x::Int|r} -> a) -> a)
toRecordRep :: forall r. {x::Int|r} -> RecordRep
toRecordRep r = RecordRep \f -> f r
test :: Array RecordRep
test = [toRecordRep {x:1}, toRecordRep {x:1, y:1}]
allTheXs = test <#> \(RecordRep r) -> r _.x
The way this works is that RecordRep wraps a function, which takes another function, which is polymorphic in r - that is, if you're looking at a RecordRep, you must be prepared to give it a function that can work with any r. toRecordRep wraps the record in such a way that its precise type is not visible on the outside, but it will be used to instantiate the generic function, which you will eventually provide. In my example such function is _.x.
Note, however, that herein lies the problem: the row r is literally not known when you get to work with an element of the array, so you can't do anything with it. Like, at all. All you can do is get the x field, because its existence is hardcoded in the signatures, but besides the x - you just don't know. And that's by design: if you want to put anything into the array, you must be prepared to get anything out of it.
Now, if you do want to do something with the values after all, you'll have to explain that by constraining r, for example:
newtype RecordRep = RecordRep (forall a. (forall r. Show {x::Int|r} => {x::Int|r} -> a) -> a)
toRecordRep :: forall r. Show {x::Int|r} => {x::Int|r} -> RecordRep
toRecordRep r = RecordRep \f -> f r
test :: Array RecordRep
test = [toRecordRep {x:1}, toRecordRep {x:1, y:1}]
showAll = test <#> \(RecordRep r) -> r show
Passing the show function like this works, because we have constrained the row r in such a way that Show {x::Int|r} must exist, and therefore, applying show to {x::Int|r} must work. Repeat for your own type classes as needed.
And here's the interesting part: since type classes are implemented as dictionaries of functions, the two options described above are actually equivalent - in both cases you end up passing around a dictionary of functions, only in the first case it's explicit, but in the second case the compiler does it for you.
Incidentally, this is how Haskell language support for this works as well.
Folloing #FyodorSoikin answer based on "existential types" and what we can find in purescript-exists we can provide yet another solution.
Finally we will be able to build an Array of records which will be "isomorphic" to:
exists tail. Array { x :: Int | tail }
Let's start with type constructor which can be used to existentially quantify over a row type (type of kind #Type). We are not able to use Exists from purescript-exists here because PureScript has no kind polymorphism and original Exists is parameterized over Type.
newtype Exists f = Exists (forall a. f (a :: #Type))
We can follow and reimplement (<Ctrl-c><Ctrl-v> ;-)) definitions from Data.Exists and build a set of tools to work with such Exists values:
module Main where
import Prelude
import Unsafe.Coerce (unsafeCoerce)
import Data.Newtype (class Newtype, unwrap)
newtype Exists f = Exists (forall a. f (a :: #Type))
mkExists :: forall f a. f a -> Exists f
mkExists r = Exists (unsafeCoerce r :: forall a. f a)
runExists :: forall b f. (forall a. f a -> b) -> Exists f -> b
runExists g (Exists f) = g f
Using them we get the ability to build an Array of Records with "any" tail but we have to wrap any such a record type in a newtype before:
newtype R t = R { x :: Int | t }
derive instance newtypeRec :: Newtype (R t) _
Now we can build an Array using mkExists:
arr :: Array (Exists R)
arr = [ mkExists (R { x: 8, y : "test"}), mkExists (R { x: 9, z: 10}) ]
and process values using runExists:
x :: Array [ Int ]
x = map (runExists (unwrap >>> _.x)) arr

Second Element of a List

From the Book programming in Scala I got the following line of code:
val second: List[ Int] => Int = { case x :: y :: _ => y }
//warning: match may not be exhaustive.
It states that this function will return the second element of a list of integers if the list is not empty or nil. Stil this part is a bit awkward to me:
case x :: y :: _
How does this ecxactly work? Does this mathches any list with at least 2 Elements and than return the second? If so can somebody still explain the syntax? I understood that :: is invoked on the right operand. So it could be written as
(_.::(y)).::(X)
Still I than don't get why this would return 2
val second: List[ Int] => Int = { case x :: y :: _ => y }
var x = List(1,2)
second(x) //returns 2
In the REPL, you can type:
scala> val list = "a" :: "b" :: Nil
list: List[String] = List(a, b)
which is to be read from right to left, and means take the end of a List (Nil), prepend String "b" and to this List ("b" :: Nil) prepend String a, a :: ("b" :: Nil) but you don't need the parens, so it can be written "a" :: "b" :: Nil.
In pattern matching you will more often see:
... list match {
case Nil => // ...
case x :: xs => // ...
}
to distinguish between empty list, and nonempty, where xs might be a rest of list, but matches Nil too, if the whole list is ("b" :: Nil) for example, then x="b" and xs=Nil.
But if list= "a" :: "b" :: Nil, then x="a" and xs=(b :: Nil).
In your example, the deconstruction is just one more step, and instead of a name like xs, the joker sign _ is used, indicating, that the name is probably not used and doesn't play a role.
The value second is of function type, it takes List[Int] and returns Int.
If the list has first element ("x"), and a second element ("y"), and whatever comes next (we don't care about it), we simply return the element "y" (which is the second element of the list).
In any other case, the function is not defined. You can check that:
scala> val second: PartialFunction[List[Int], Int] = {
| case x :: y :: _ => y
| }
second: PartialFunction[List[Int],Int] = <function1>
scala> second.isDefinedAt(List(1,2,3))
res18: Boolean = true
scala> second.isDefinedAt(List(1,2))
res19: Boolean = true
scala> second.isDefinedAt(List(0))
res20: Boolean = false
First of all. When you think about pattern matching you should think about matching a structure.
The first part of the case statement describes a structure. This structure may describe one or more things (variables) which are useful to deriving your result.
In your example, you are interested in deriving the second element of a list. A shorthand to build a list in Scala is to use :: method (also called cons). :: can also be used to describe a structure in case statement. At this time, you shouldn't think about evaluation of the :: method in first part of case. May be that's why you are saying about evaluation of _.::(y).::(x). The :: cons operator help us describe the structure of the list in terms of its elements. In this case, the first element (x) , the second element (y) and the rest of it (_ wildcard). We are interested in a structure that is a list with at least 2 elements and the third can be anything - a Nil to indicate end of list or another element - hence the wildcard.
The second part of the case statement, uses the second element to derive the result (y).
More on List and Consing
List in Scala is similar to a LinkedList. You know about the first element called head and start of the rest of the list. When traversing the linked list you stop if the rest of the list is Nil. This :: cons operator helps us visualise the structure of the linked list. Although Scala compile would actually be calling :: methods evaluating from right to left as you described _.::(y).::(x)
As an aside, you might have already noticed that the Scala compiler might be complain that your match isn't exhaustive. This means that this second method would work for list of any size. Because there isn't any case statement to describe list with zero or one element. Also, as mentioned in comments of previous answers, if you aren't interested in first element you can describe it as a wildcard _.
case _ :: y :: _ => y
I hope this helped.
If you see the structure of list in scala its head::tail, first element is treated as head and all remaining ones as tail(Nil will be the last element of tail). whenever you do x::y::_, x will match the head of the list and remaining will be tail and again y will match the head of the next list(tail of first list)
eg:
val l = List(1,2,3,4,5)
you can see this list in differnt ways:
1::2::3::4::5::Nil
1::List(2,3,4,5)
1::2::List(2,3,4,5)
and so on
So try matching the pattern. In your question y will give the second element

Pattern matching on the result of type computing functions in idris

Consider the following fragment:
import Data.List
%default total
x : Elem 1 [1, 2]
x = Here
type : Type
type = Elem 1 [1, 2]
y : type
y = Here
This gives the error:
When checking right hand side of y:
Type mismatch between
Elem x (x :: xs) (Type of Here)
and
iType (Expected type)
The type of y, when queried, is:
type : Type
-----------
y : type
Is it possible to force type to be evaluated during or before the type ascription of y, so that the type of y is Elem 1 [1, 2]?
My use case is that I want to be able to define generic predicates that return the right proposition terms for proofs, for example:
subset : List a -> List a -> Type
subset xs ys = (e : a) -> Elem e xs -> Elem e ys
thm_filter_subset : subset (filter p xs) xs
Names in type declarations which begin with a lower case letter are implicitly bound, so it's treating 'type' as a type parameter. You can either give 'type' a new name which begins with a capital (by convention this is what most people do in Idris) or you can explicitly qualify the name with the module it's in (Main, here).
Idris used to try guessing whether names such as 'type' were intended as an implicit or intended to refer to the global, as here. There's all kinds of voodoo involved in getting this right though, so it often failed, and so it now implements this much simpler rule. It's slightly annoying in cases such as this, but the alternative behaviour was more often annoying (and harder to explain).

Scala fold over String results in "type mismatch; found: Any"

I'm playing around with folds in Scala and, for whatever reason, ended up trying to test whether a String contains only unique characters by doing the following:
str
.fold(""){ (x, y) => if (!(x contains y)) x + y else x }
.size == str.size
This results in the error
error: type mismatch;
found: Any
required: String
apparently pointing to the value of y.
Can anyone provide insight into this?
I wouldn't have expected this behavior, and the closest answer I could find with respect to this was "Scala assumes wrong type when using foldLeft," which is similar, but doesn't quite clarify things.
You should use foldLeft instead of fold:
str
.foldLeft(""){ (x, y) => if (!(x contains y)) x + y else x }
.size == str.size
the signature for fold is:
fold[A1 >: Char](z: A1)(op: (A1, A1) ⇒ A1): A1
So fold expects the element type to be a lower bound on the accumulator type. The element type is Char in the case of String, so the possible types for A1 are Char, AnyVal and Any. You pass a String so Any is the only common type, which means x and y have type Any, which does not have a contains method.
You need to the accumulator type to be different from the element type so you need to use foldLeft.