I'm trying to translate some python code to haskell. However I reached a point where I'm not sure how to proceed.
if len(prod) % 2 == 0:
ss = float(1.5 * count_vowels(cust))
else:
ss = float(count_consonants(cust)) # muliplicaton by 1 is implied.
if len(cust_factors.intersection(prod_factors)) > 0:
ss *= 1.5
return ss
I've tried to translate it to this:
if odd length prod
then ss = countConsonants cust
else ss = countVowels cust
if length (cust intersect
prod) > 0
then ss = 1.5 * ss
else Nothing
return ss
But I keep getting errors of:
parse error on input `='
Any help or words of wisdom on this would be greatly appreciated.
If you're new to the syntax that's used in the code sample, if (int i = 5) { is a perfectly valid way of declaring and defining a variable, then using it inside the given if statement. It allows us to write terser, clearer code, while also avoiding limiting the scope of a variable.
python allows creation of variables in an if... elif... else... clause, so that they can be used also outside the conditional block. This is also true for nested conditionals.
No. That is not allowed in C. According to the ANSI C Grammar, the grammar for the if statement is IF '(' expression ')' statement . expression cannot resolve to declaration , so there is no way to put a declaration in an if statement like in your example.
If you define the variable inside an if statement, than it'll only be visible inside the scope of the if statement, which includes the statement itself plus child statements. You should define the variable outside the scope and then update its value inside the if statement.
Don't think of programming in Haskell as "if this, then do that, then do the other thing" — the entire idea of doing things in a sequence is imperative. You're not checking a condition and then defining a variable — you're just calculating a result that depends on a condition. In functional programming, if
is an expression and variables are assigned the result of an expression, not assigned inside it.
The most direct translation would be:
let ss = if odd $ length prod
then countConsonants cust
else countVowels cust
in if length (cust `intersect` prod) > 0
then Just $ 1.5 * ss
else Nothing
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With