1
votes

I tried to use this code to scramble the characters into different characters and return a new list with those new characters. However, I keep getting errors saying : "a list but here has type char" on line 3, "a list list but given a char list" on the line 13 . Not sure how to fix this. Thanks in advance for the help.

 let _scram x =
      match x with
      | [] -> [] // line 3
      | 's' -> 'v'
      | 'a' -> 's'
      | 'e' -> 'o'
      | '_' -> '_'

 let rec scramble L P =
      match L with
      | [] -> P
      | hd::t1 ->  scramble t1 (P @ (_scram hd)) 

 let L = 
      let p = ['h'; 'e'; 'l'; 'l'; 'o'] //line 13
      scramble p []
2

2 Answers

2
votes

That's because you are calling the _scram as second operand of the (@) operator which concatenates two lists, so it infers that the whole expression has to be a list.

A quick fix is to enclose it into a list: (P @ [_scram hd]), this way _scram hd is inferred to be an element (in this case a char).

Then you will discover your next error, the catch-all wildcard is in quotes, and even if it wouldn't, you can't use it to bind a value to be used later.

So you can change it to | c -> c.

Then your code will be like this:

let _scram x =
      match x with
      | 's' -> 'v'
      | 'a' -> 's'
      | 'e' -> 'o'
      |  c  ->  c

let rec scramble L P =
    match L with
    | [] -> P
    | hd::t1 ->  scramble t1 (P @ [_scram hd]) 

let L = 
    let p = ['h'; 'e'; 'l'; 'l'; 'o']
    scramble p []
1
votes

F# code is defined sequentially. The first error indicates there is some problem with the code upto that point, the definition of _scram. The line | [] -> [] implies that _scram takes lists to lists. The next line | 's' -> 'v' implies that _scram takes chars to chars. That is incompatible and that explains the error.