-4

I'm new to Haskell and I'm not sure how to work around the If-Else, for example:

function str = if ((length str) = 2) then (....)

In java we would:

if (str.length =2){
    str = "2"}
else { str ="1"}

How do you write it in haskell?

Yuki2222
  • 33
  • 4
  • 1
    What do you mean by "work around the if-Else"? It is very unclear what your example is supposed to illustrate. – molbdnilo Apr 20 '21 at 08:38
  • see example in Java – Yuki2222 Apr 20 '21 at 08:48
  • 3
    It's still not a good illustration since you're using assignments. What is the actual problem you're trying to solve? (You should probably take a look at the tips at [Getting started with Haskell](https://stackoverflow.com/questions/1012573/getting-started-with-haskell). Trying to program in Haskell while thinking in Java is only going to be frustrating.) – molbdnilo Apr 20 '21 at 08:58
  • 1
    you question is a bit confusing because: In your Haskell example you don't include a `else` branch, but in Haskell you *need* one. On the other hand in Java you *include* the `else` branch but you would not need it there. – Random Dev Apr 20 '21 at 09:07
  • Also (just in Java?) you want to use `==` to compare to values for *equality* - I think your Java-code would not work either (sorry never programmed in Java but you need `;` also right?). – Random Dev Apr 20 '21 at 09:09
  • 1
    Note that assigning to parameters does nothing in Java. That is, `void foo(String str) { if (str.length == 2) { str = "2"; } else { str = "1"; } }` (which I assume is the code you meant because your code is incomplete and contains syntax errors) is exactly equivalent to `void foo(String str) { /* do nothing */ }`. The Haskell equivalent of that would be `foo _ = ()`. – sepp2k Apr 20 '21 at 09:11

1 Answers1

3

You can use Guards:

fnc :: String -> String
fnc s | length s == 2 = ...
      | otherwise = ...

More to Guards


Or conditions

fnc :: String -> String
fnc s = if length s == 2 then ... else ...

It is also possible to use pattern matching, more here.

There are several ways to achieve conditions (e.g. case of) in Haskell.

Jozott
  • 2,367
  • 2
  • 14
  • 28