purescript anonymous function arguments on nested records? - purescript

Is it possible to apply anonymous function arguments to nested records somehow in the followign way?
type UName = {fname :: String, lname :: String}
type XName = { xname :: UName, addr :: String}
updateU = _ { xname : { fname : _ } } -- not ok
-- or
updateU = _ { xname.fname = _ } -- not ok
-- or
updateU = _ { xname : fname = _ } } -- not ok
Above trials say that context is invalid. Aim is to implement:
updateU = \x -> { xname : { fname : x } }

The shortest version uses nested record updates and looks like this:
updateU :: XName -> String -> XName
updateU = _ { xname { fname = _ } }

Related

How can I extract numbers from string in Swift in a specific way

I'm struggling to extract numbers from a string in Swift. I'm doing the following:
let expression: String = "abc123aa223bb45"
for (indx, ch) in expression.enumerated() {
if ch.isLetter { continue }
else if ch.isNumber {
var val: Int = 0
while(indx < expression.count && ch.isNumber){
val = val * 10 + (ch.asciiValue - 48)
//how can I proceed and increment both indx and ch ...
}
// here I'm going to do smthing with every extracted number
}
}
Can somebody help me finish this problem I've reached?
I also use the extension
extension Character {
var asciiValue: Int {
get {
let s = String(self).unicodeScalars
return Int(s[s.startIndex].value)
}
}
}
as you can see in the posted fragment of code
The following code snippet will extract numbers from a String
let expression: String = "abc123aa223bb45"
let stringArray = expression.components(separatedBy: CharacterSet.decimalDigits.inverted)
for item in stringArray {
if let number = Int(item) {
print(number)
}
}
You could also make an extension of Int that has a function like
extension Int {
static func parse(from string: String) -> Int? {
return Int(string.components(separatedBy: CharacterSet.decimalDigits.inverted).joined())
}
}
and can be use like this
let expression: String = "abc123aa223bb45"
if let number = Int.parse(from: expression) {
print(number)
}
I'm trying to write a program that evaluates expression with braces and operators: ^,+,-,/,*
But I'm having some issues ( I've done this many times with C++ and C# but I cannot manage to do it with swift. It really gives me a huge headache ):
import Foundation
extension Character {
var asciiValue: Int {
get {
let s = String(self).unicodeScalars
return Int(s[s.startIndex].value)
}
}
}
precedencegroup PowerPrecedence { higherThan: MultiplicationPrecedence }
infix operator ^^ : PowerPrecedence
func ^^ (radix: Double, power: Int) -> Double {
return (pow(Double(radix), Double(power)))
}
func calc(a: Double, b: Double, o: Character) -> Double {
switch o {
case "+":
return a + b
case "-":
return a - b
case "/":
return a / b
case "*":
return a * b
case "^":
return a ^^ Int(b)
default:
return 0
}
}
func nice(o: Character) -> Int {
if o == "-" || o == "+" { return 1 }
if o == "*" || o == "/" { return 2 }
if o == "^" { return 3 }
return 2020
}
func evaluate(expression: String) -> Double {
var vals = [Double]()
var ops = [Character]()
for (indx, ch) in expression.enumerated() {
if ch == " " { continue }
else if ch == "(" { ops.append(ch) }
else if ch.isNumber {
var val: Int = 0
while(indx < expression.count && ch.isNumber){
val = val * 10 + ch.asciiValue - 48 // gives strange error
//TODO increment indx and ch
}
vals.append(Double(val))
} else if ch == ")" {
while !ops.isEmpty && ops.last != "(" {
let val_2: Double = vals.popLast()!
let val_1: Double = vals.popLast()!
let op: Character = ops.popLast()!
vals.append(calc(a: val_1, b: val_2, o: op))
}
if !ops.isEmpty { _ = ops.popLast() } // opening brace
} else {
while(!ops.isEmpty && nice(o: ops.last!) >= nice(o: ch)){
let val_2: Double = vals.popLast()!
let val_1: Double = vals.popLast()!
let op: Character = ops.popLast()!
vals.append(calc(a: val_1, b: val_2, o: op))
}
ops.append(ch);
}
}
while !ops.isEmpty {
let val_2: Double = vals.popLast()!
let val_1: Double = vals.popLast()!
let op: Character = ops.popLast()!
vals.append(calc(a: val_1, b: val_2, o: op))
}
return vals.last!
}
let exp: String = "2^3+(2+3)"
print(evaluate(expression: exp))

swift function dynamic apply argument

I am trying to implement function can apply arguments. I read many reference, its possible how ever I want to make one for all situations, no sure if its posable.
For example,
infix operator <<< ;
func <<<< T >( lhs : ( T ) -> T , rhs : [ T ] ) -> T {
return lhs( rhs[ 0 ] ) ;
} ;
func Foo ( _ a : Int )-> Int { return a ; }
Foo<<<[ Int ]
This is totally works, however, it will not with different kind of functions, like with different type of arguments and return types.
For example
func Foo ( _ a : Int , _ b : Int )-> Int { return a ; } ;
or maybe
func Foo ( _ a : Int , _ b : Any , _ c : String )-> Any { return Any ; } ;
then
var args = [ Any ] ;
Foo<<<args ; // to make this work
Any advises? Thank you very much.
I am not sure if this is what you want:
infix operator <<<
func <<< <U,V> (lhs: (U...) -> V, rhs: [U]) -> V {
return lhs(rhs[0])
}
For example:
func Foo (_ a: Int...) -> Double {
return a.map { 1.5 * Double($0) }
.reduce(0, +)
}
Foo <<< [3, 5] //4.5
Foo <<< [1] //1.5

Sum and For loop together in Swift

I want to know how many common characters in the given sets.
Input: J = "aA", S = "aAAbbbb"
Output: 3
In the python solution for this as follows:
lookup = set(J)
return sum(s in lookup for s in S)
I have following solution in Swift it works, but it looks too wordy. I want to learn shorter way of it.
class Solution {
func checkInItems(_ J: String, _ S: String) -> Int {
let lookup = Set(J) ;
var sy = 0;
for c in S
{
if lookup.contains(c)
{
sy += 1;
}
}
return sy;
}
}
As a small variation of Sh_Khan's answer you can use reduce to
count the number of matching elements without creating an intermediate
array:
func checkInItems(_ J: String, _ S: String) -> Int {
let lookup = Set(J)
return S.reduce(0) { lookup.contains($1) ? $0 + 1 : $0 }
}
In Swift 5 there will be a count(where:) sequence method for this purpose,
see SE-0220 count(where:).
You can try
class Solution {
func checkInItems(_ J: String, _ S: String) -> Int {
let lookup = Set(J)
return S.filter { lookup.contains($0) }.count
}
}

How to share arguments ( pass & return in both direction) between closure and method like shown below groovy code?

Groovy code: how to pass and return arguments or values
def method (int a, Closure c) {
Query q = new Query()
c.delegate = q
c()
//label 1: pass a to label 2 and get str from there
}
class Query
{
void key (String str) {
//label 2: return str and get a to method label 1.
}
}
method(5) {
key "got"
}
How to get access on both labels in above shown groovy code.
I don't know how to use some keys like .call() return inside this closure.
Update 1:
def method (int a, Closure c) {
Query q = new Query()
c.delegate = q
c.call(a)
def str = q.str
println str
}
class Query
{
def str
def a
void key (String str) {
this.str = str
this.a=a
println a
}
}
method(5) {
key "got"
}
Actual Output:
null
got
Expected Output:
5
got
How to solve this ?
How about something like
def method (int a, Closure c) {
Query q = new Query()
q.a = a
c.delegate = q
c.call()
def str = q.str
println str
}
class Query
{
def str
def a
void key (String str) {
this.str = str
println a
}
}
method(5) {
key "got"
}

why i have the error "No instance for (Ord Documento) arising from a use of ‘insert" wit haskell

Im beginner with haskell and im trying to execute my method mostrarDocumento, setting Documentos and String(year), and the method should return all documents that have the same year , but i having the error :
No instance for (Ord Documento) arising from a use of ‘insert’
In a stmt of a 'do' block:
insert docu (mostrarDocumento' documentos anno)
In the expression:
do { insert docu (mostrarDocumento' documentos anno) }
In the expression:
if esAnnoIgual docu anno then
do { insert docu (mostrarDocumento' documentos anno) }
else
mostrarDocumento' documentos anno
Someone can help me with my code?
module Documento where
import Data.List
import Data.Function (on)
import System.IO()
type Revista = String
type IdD = String
type Anno = String
type Titulo = String
type Resumen = String
type Secciones = [String]
data Documento = D (Revista, IdD, Anno, Titulo, Resumen, Secciones)deriving Show
type Documentos = [Documento]
anio :: Documento -> Anno
anio (D (_,_,anio,_,_,_)) = anio
pintarDocOrd :: Documentos -> IO()
pintarDocOrd [] = return ()
pintarDocOrd (dc:dcs) = do
print dc
pintarDocOrd dcs
mostrarDocumeto :: Documentos -> String-> IO()
mostrarDocumeto [] _ = return ()
mostrarDocumeto documentos anno = do
let documento = mostrarDocumento' documentos anno
pintarDocOrd documento
mostrarDocumento' :: Documentos -> String -> Documentos
mostrarDocumento' [] _ = []
mostrarDocumento' (docu:documentos) anno =
if esAnnoIgual docu anno then do
insert docu (mostrarDocumento' documentos anno)
else
mostrarDocumento' documentos anno
esAnnoIgual :: Documento -> String -> Bool
esAnnoIgual documento anno
| anio documento == anno = True
| otherwise = False
As you can see from the documentation:
insert :: Ord a => a -> [a] -> [a]
So insert works on a list of as, but only if that a is of typeclass Ord, i.e. that have an order defined on them. So try:
data Documento = ... deriving (Show, Ord)
I have a feeling this is what you are trying to do:
mostrarDocumento' :: Documentos -> String -> Documentos
mostrarDocumento' [] _ = []
mostrarDocumento' (docu:documentos) anno =
if esAnnoIgual docu anno
then docu : (mostrarDocumento' documentos anno)
else mostrarDocumento' documentos anno
which is the same as:
mostrarDocumento' docs = filter (\d -> esAnnoIgual d anno) docs