Codewars - Swift Solution (Multiply Function) - swift

func multiply(_ a: Double, _ b: Double) -> Double {
a * b
}
What's wrong with this part of code? I am having trouble trying to figure it out.

Edit: in newer versions of Swift, OP's code works too, since return is no longer needed if there is only one expression in the body of a funcion/variable. Details here.
You are not doing anything with the result.
-> Double indicates that this function should return a Double. For that, you should use the return keyword:
func multiply(_ a: Double, _ b: Double) -> Double {
return a * b
}

Try this
public class Multiply
{
public double multiply(double a, double b)
{ return a * b;}
}
public class Multiply
{
public static Double multiply(Double a, Double b)
{
return a * b;
}
}

Related

Simplifying Swift Enum

After experimenting with currying in Swift, I came up with the code below. I want to see if it's possible to simplify this enum Operate. Currently, I need to initialize like this:
let multiply = Operate.Multiply.op
I would prefer to have each case have an associated value that directly returns a closure without having to do this hacky switch block. Is this possible?
Here's some code that you can run in a Swift playground:
import Foundation
enum Operate {
case Plus
case Minus
case Multiply
case unsafeDivide
var op: (Double) -> (Double) -> Double {
get {
switch self {
case .Plus:
return { n in
return { n + $0}
}
case .Minus:
return { n in
return { n - $0}
}
case .Multiply:
return { n in
return { n * $0}
}
case .unsafeDivide:
return { n in
return { n / $0 }
}
}
}
}
}
let multiply = Operate.Multiply.op
let plus = Operate.Plus.op
let unsafeDivide = Operate.unsafeDivide.op
// 3 + (16 * 2) -> 35
plus(3)(multiply(16)(2))
Bonus: How can I handle errors with unsafeDivide in a 'Swiftly' manner, that is, prevent this:
let unsafeDivide = Operate.unsafeDivide.op
unsafeDivide(2)(0)
What you seem to be doing is currying. You remove a lot of duplicated code by extracting a curry function:
func curry<A,B,C>(_ f: #escaping (A, B) -> C) -> (A) -> (B) -> C {
return { a in { b in f(a, b) } }
}
// ...
var op: (Double) -> (Double) -> Double {
switch self {
case .plus: // please follow Swift naming conventions, enum cases start with a lowercase
return curry(+)
case .minus:
return curry(-)
case .multiply:
return curry(*)
case .unsafeDivide:
return curry(/)
}
}
That already looks a lot nicer. You seem to not like switch statements, so here's how you'd do it with a dictionary:
var op: (Double) -> (Double) -> Double {
let dict: [Operate: (Double, Double) -> Double] =
[.plus: (+), .minus: (-), .multiply: (*), .unsafeDivide: (/)]
return curry(dict[self]!)
}
In fact, you can use the new callAsFunction feature in Swift 5.2 to omit even the word op on the caller side:
func callAsFunction(_ a: Double) -> (Double) -> Double {
op(a)
}
This allows you to do:
Operator.multiply(2)(3)
Using associated values is another way:
enum Operate {
case plus(Double)
case minus(Double)
case multiply(Double)
case unsafeDivide(Double)
func callAsFunction(_ b: Double) -> Double {
switch self {
case .plus(let a):
return a + b
case .minus(let a):
return a - b
case .multiply(let a):
return a * b
case .unsafeDivide(let a):
return a / b
}
}
}
But I personally don't like it because having associated values means that you can't simply use == to compare enum values, among other restrictions.
Preventing dividing by 0 at compile time is impossible, because the values you pass in might not be compile time constants. If you just want to check for compile time constants, then you might need a static code analyser like SwiftLint. At runtime, division of the Double 0 is well-defined by the IEEE standard anyway. It won't crash or anything.

Calling Standard Library Functions [duplicate]

I was trying to write an Int extension to clamp an Int to a specific range, like this:
extension Int {
func clamp(left: Int, right: Int) -> Int {
return min(max(self, left), right)
}
}
I was getting a compiler error and after a while I realised that min is being interpreted here as Int.min, which is a constant for the lowest Int.
I can reimplement this avoiding min/max but I'm curious: is there a way I can reference those from an Int extension?
You can prepend the module name, in this case Swift:
extension Int {
func clamp(left: Int, right: Int) -> Int {
return Swift.min(Swift.max(self, left), right)
}
}
And just for fun: You get the same result with
extension Int {
func clamp(left: Int, right: Int) -> Int {
return (left ... right).clamp(self ... self).start
}
}
using the clamp() method from ClosedInterval.
You could create a function myMin<T>(a: T, b: T) that calls min and use that in your extension.

Using overridden math function

Trying to compile this code
pow(10,2)
struct Test {
var i:Int
func pow(_ p:Int) -> Int { return pow(i,p) }
}
var s = Test(i:10)
s.pow(2)
gives me a compiler error. Obviously the standard math.h function pow was blinded out by Swift's scoping rules. This rather smells like a compiler error since the math.h version of pow has a different signature. Is there any way to invoke it, though?
There are two problems: The first is how pow(i,p) is resolved.
As described in Swift 3.0: compiler error when calling global func min<T>(T,T) in Array or Dictionary extension, this
can be solved by prepending the module name to the function call.
The second problem is that there is no pow function taking
two integer arguments. There is
public func powf(_: Float, _: Float) -> Float
public func pow(_: Double, _: Double) -> Double
in the standard math library, and
public func pow(_ x: Decimal, _ y: Int) -> Decimal
in the Foundation library. So you have to choose which one to use,
for example:
struct Test {
var i:Int
func pow(_ p:Int) -> Int {
return lrint(Darwin.pow(Double(i),Double(p)))
}
}
which converts the arguments to Double and rounds the result
back to Int.
Alternatively, use iterated multiplication:
struct Test {
var i: Int
func pow(_ p:Int) -> Int {
return (0..<p).reduce(1) { $0.0 * i }
}
}
I observed at https://codereview.stackexchange.com/a/142850/35991 that
this is faster for small exponents. Your mileage may vary.

Is it possible to access a shadowed top level function in Swift?

I was trying to write an Int extension to clamp an Int to a specific range, like this:
extension Int {
func clamp(left: Int, right: Int) -> Int {
return min(max(self, left), right)
}
}
I was getting a compiler error and after a while I realised that min is being interpreted here as Int.min, which is a constant for the lowest Int.
I can reimplement this avoiding min/max but I'm curious: is there a way I can reference those from an Int extension?
You can prepend the module name, in this case Swift:
extension Int {
func clamp(left: Int, right: Int) -> Int {
return Swift.min(Swift.max(self, left), right)
}
}
And just for fun: You get the same result with
extension Int {
func clamp(left: Int, right: Int) -> Int {
return (left ... right).clamp(self ... self).start
}
}
using the clamp() method from ClosedInterval.
You could create a function myMin<T>(a: T, b: T) that calls min and use that in your extension.

Swift: why 'subscript(var digitIndex: Int) -> Int' is a valid function signature?

This piece of code comes from Swift documentation https://developer.apple.com/library/prerelease/mac/documentation/Swift/Conceptual/Swift_Programming_Language/Extensions.html
extension Int {
subscript(var digitIndex: Int) -> Int {
var decimalBase = 1
while digitIndex > 0 {
decimalBase *= 10
--digitIndex
}
return (self / decimalBase) % 10
}
}
Apparently var is a reserved word, so why it is legal to declare: subscript(var digitIndex: Int) -> Int?
If I change the signature to subscript(#digitIndex: Int) -> Int, I will get this compiler error:
My questions are:
1) why the signature is valid?
2) why my change causes an exception?
Declaring a function argument with var means that it can be modified, is not a constant. In your case, without using var, you had a constant argument but you attempted to decrement it. Thus the error.
Your two cases are:
func foo (x: int) { /* x is a constant, like `let x: int` */ }
func foo (var x: int) { /* x is not a constant */ }