如何基于if/then/else语句定义变量

Bry*_*yce 5 haskell functional-programming if-statement

我正在尝试将一些python代码翻译为haskell.但是我达到了一个我不确定如何继续的地步.

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
Run Code Online (Sandbox Code Playgroud)

我试图把它翻译成这个:


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

但我不断收到错误:

输入`='时解析错误

任何有关此问题的帮助或言论都将受到高度赞赏.

Chu*_*uck 14

不要把Haskell中的编程想象为"如果这样,那么那样做,那么做另一件事" - 按顺序执行操作的整个想法是必不可少的.您没有检查条件然后定义变量 - 您只是计算取决于条件的结果.在函数式编程中,if是一个表达式,变量被赋予表达式的结果,而不是在其中赋值.

最直接的翻译是:

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
Run Code Online (Sandbox Code Playgroud)


Gab*_*abe 6

在Haskell中,if是表达式,而不是语句.这意味着它返回一个值(如函数)而不是执行操作.这是翻译代码的一种方法:

ss = if odd length prod 
    then countConsinants cust 
    else countVowels cust 
return if length ( cust intersect prod) > 0 
    then Just $ 1.5 * ss 
    else Nothing
Run Code Online (Sandbox Code Playgroud)

这是另一种方式:

return if length ( cust intersect prod) > 0 
    then Just $ 1.5 * if odd length prod 
        then countConsinants cust 
        else countVowels cust 
    else Nothing
Run Code Online (Sandbox Code Playgroud)

但是,正如Matt指出的那样,您的Python代码不会返回None.每个代码路径都设置ss为一个数字.如果这是它应该如何工作,这是一个Haskell翻译:

let ss = if odd $ length prod 
           then countConsonants cust 
           else countVowels cust 
in if length (cust `intersect` prod) > 0 
     then 1.5 * ss 
     else ss
Run Code Online (Sandbox Code Playgroud)