locked
how to convert this function into a list of tuple RRS feed

  • Question

  • change f_fn to  ("A", "C") :: ("B" ,"C") :: ("C", "D") :: ("D", "E") :: [] 

    let f_fn =  function   
                | Just("A") -> Just("C")
                | Just("B") -> Just("C")
                | Just("C") -> Just("D")
                | Just("D") -> Just("E")

    if impossible, can 

    ("A", "C") :: ("B" ,"C") :: ("C", "D") :: ("D", "E") :: []

    convert to f_fn?


    成功者拿未來換現在,失敗者用現在換未來. 原來無求品自高, 機到有求先得手. She likes you.


    Tuesday, May 13, 2014 7:46 AM

Answers

  • I'm presuming this is run-time.

    Provided you know the list of possible input values, then just map over them like this

    let table = ["A"; "B"; "C" ; "D"] |> List.map (fun x -> (x, f_fn (Just x))) |> List.map (fun (x,y) -> match y with Just q -> (x,q));;

    It's easier in reverse -- you can use the list of pairs to create a Map and do look-ups there

    let f_fn' =  (fun x -> match x with Just q -> Just (Map.find q (Map.ofList table)));;
    where `table` in the second fragment is the value from the first one.



    • Edited by Mr. Tines Tuesday, May 13, 2014 6:50 PM formatting
    • Marked as answer by Map to new space Wednesday, May 14, 2014 10:30 AM
    Tuesday, May 13, 2014 6:49 PM

All replies

  • I'm presuming this is run-time.

    Provided you know the list of possible input values, then just map over them like this

    let table = ["A"; "B"; "C" ; "D"] |> List.map (fun x -> (x, f_fn (Just x))) |> List.map (fun (x,y) -> match y with Just q -> (x,q));;

    It's easier in reverse -- you can use the list of pairs to create a Map and do look-ups there

    let f_fn' =  (fun x -> match x with Just q -> Just (Map.find q (Map.ofList table)));;
    where `table` in the second fragment is the value from the first one.



    • Edited by Mr. Tines Tuesday, May 13, 2014 6:50 PM formatting
    • Marked as answer by Map to new space Wednesday, May 14, 2014 10:30 AM
    Tuesday, May 13, 2014 6:49 PM
  • Crazy code

    why the left hand side Just q know what to use in right hand side' s List item?

     Just q -> Just (Map.find q (Map.ofList table)))


    成功者拿未來換現在,失敗者用現在換未來. 原來無求品自高, 機到有求先得手. She likes you.


    Wednesday, May 14, 2014 10:31 AM
  • The code is set up so that `f_fn'` was an exact replacement for `f_fn`, at least for arguments that give an answer rather than an error.

    The match with `Just q` takes any `Just [whatever]` and extracts the `[whatever]` as the name `q`.   Having that value, we then look it up (`Map.find`) in the table of string to string values (`Map.ofList table`), and if it's there return it as a `Just [result]` as required.

    It's called an "Identifier Pattern" in the MSDN page about F# Pattern Matching.

    Wednesday, May 14, 2014 1:18 PM