Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a variable based on an if/then/else statement

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.

like image 733
Bryce Avatar asked Aug 24 '10 04:08

Bryce


People also ask

Can you define a variable in an if statement?

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.

Can you define variable in IF statement Python?

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.

Can you declare variables in an if statement in C?

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.

How do you use a variable outside of an if statement in Java?

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.


1 Answers

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
like image 60
Chuck Avatar answered Nov 10 '22 01:11

Chuck