Search code examples
haskelltypeerror

Take all digits from a string and present them in a list


I was doing some Haskell exercises but can't solve the last one.

I need to recursively define functions that are already defined in the Data.Char module.

The last function I need to define is of this type:

nums :: String -> [Int]

Here is the (translated) question:

Using functions from the Data.Char module, define recursively the following functions:

(c) nums :: String -> [Int] which receives a string and outputs a list with the numerical digits that occur on that string, by the same order.

--This is my code

numbers :: String -> [Int]
numbers [] = []
numbers (l:ls) = if ord l >= 48 && ord l <= 57
                 then l : (numbers ls)
                 else (numbers ls)

I've been getting this error on the interpreter:

pratica3.hs:137:14:
    Couldn't match expected type `Int' with actual type `Char'
    In the first argument of `(:)', namely `l'
    In the expression: l : (numbers ls)
    In the expression:
      if ord l >= 48 && ord l <= 57 then
          l : (numbers ls)
      else
          (numbers ls)
Failed, modules loaded: none.

Thank you.


Solution

  • Ok,

    The solution is:

    numbers :: String -> [Int]
    numbers [] = []
    numbers (l:ls) = if ord l >= 48 && ord l <= 57
        then (ord l - 48): (numbers ls)
        else (numbers ls)
    

    This is correct.